module Stream ( Stream(..) , append , empty , fromList , infinite , merge ) where import Tree (Tree(..), Structure(..)) data Stream a = Stream [(a, Stream a)] deriving Show instance Functor Stream where fmap f (Stream pairs) = Stream $ (\(a, stream) -> (f a, fmap f stream)) <$> pairs instance Tree Stream where getStructure (Stream []) = Leaf getStructure (Stream pairs) = Node $ (\(s, stream) -> (s, getStructure stream)) <$> pairs empty :: Stream a empty = fromList [] append :: Stream a -> Stream a -> Stream a append (Stream []) b = b append (Stream pairs) b = Stream $ (\(a, stream) -> (a, stream `append` b)) <$> pairs fromList :: [a] -> Stream a fromList [] = Stream [] fromList (pair:pairs) = Stream [(pair, fromList pairs)] infinite :: a -> Stream a infinite a = Stream [(a, infinite a)] merge :: Eq a => Stream a -> Stream a -> Stream a merge (Stream aPairs) (Stream bPairs) = Stream $ foldl mergeOrAdd aPairs bPairs where openAt _ l [] = (l, []) openAt p up l@(x:xs) = if p x then (up, l) else openAt p (x:up) xs zipUp ([], l) = l zipUp (x:xs, l) = zipUp (xs, x:l) mergeOrAdd accumulator (b, bStream) = zipUp $ case openAt ((== b) . fst) [] accumulator of (up, []) -> (up, [(b, bStream)]) (up, (x, xStream):down) -> (up, (x, merge xStream bStream):down)