Mainate/src/Stream.hs

49 lines
1.3 KiB
Haskell
Raw Permalink Normal View History

2019-05-03 07:58:44 +02:00
module Stream (
Stream(..)
, append
, empty
, fromList
, infinite
, merge
2019-05-03 07:58:44 +02:00
) where
import Tree (Tree(..), Structure(..))
2019-05-03 07:58:44 +02:00
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
2019-05-03 07:58:44 +02:00
fromList :: [a] -> Stream a
fromList [] = Stream []
fromList (pair:pairs) = Stream [(pair, fromList pairs)]
infinite :: a -> Stream a
infinite a = Stream [(a, infinite a)]
2019-05-03 19:07:40 +02:00
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)