2019-05-03 07:58:44 +02:00
|
|
|
module Stream (
|
2019-05-03 19:17:17 +02:00
|
|
|
Stream(..)
|
2019-05-06 08:17:49 +02:00
|
|
|
, append
|
|
|
|
, empty
|
2019-05-03 19:17:17 +02:00
|
|
|
, fromList
|
|
|
|
, infinite
|
|
|
|
, merge
|
2019-05-03 07:58:44 +02:00
|
|
|
) where
|
|
|
|
|
2019-05-06 08:17:49 +02:00
|
|
|
import Tree (Tree(..), Structure(..))
|
2019-05-03 07:58:44 +02:00
|
|
|
|
|
|
|
data Stream a = Stream [(a, Stream a)] deriving Show
|
|
|
|
|
2019-05-06 08:17:49 +02:00
|
|
|
instance Functor Stream where
|
|
|
|
fmap f (Stream pairs) =
|
|
|
|
Stream $ (\(a, stream) -> (f a, fmap f stream)) <$> pairs
|
|
|
|
|
|
|
|
instance Tree Stream where
|
2019-05-09 16:42:42 +02:00
|
|
|
getStructure (Stream []) = Leaf
|
2019-05-06 08:17:49 +02:00
|
|
|
getStructure (Stream pairs) =
|
|
|
|
Node $ (\(s, stream) -> (s, getStructure stream)) <$> pairs
|
|
|
|
|
2019-05-05 12:27:03 +02:00
|
|
|
empty :: Stream a
|
|
|
|
empty = fromList []
|
|
|
|
|
|
|
|
append :: Stream a -> Stream a -> Stream a
|
|
|
|
append (Stream []) b = b
|
2019-05-06 08:17:49 +02:00
|
|
|
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)
|