@@ -0,0 +1,68 @@
1+module Lazy.Stream ( hd, tl, mkStream, repeat, cycle
2+ , map, apply, zip, zipWith, iterate
3+ , take, observeWhen
4+ ) where
5+
6+{-| Library for Infinite Streams -}
7+
8+import Basics ((.), (<|), (-))
9+import open Lazy
10+import Signal ((<~), foldp, Signal)
11+
12+data Stream a = S (Lazy { hd : a, tl : Stream a })
13+
14+hd : Stream a -> a
15+hd (S t) = (run t).hd
16+
17+tl : Stream a -> Stream a
18+tl (S t) = (run t).tl
19+
20+mkStream : (() -> { hd : a, tl : Stream a }) -> Stream a
21+mkStream = S . thunk
22+
23+repeat : a -> Stream a
24+repeat x = mkStream <| \() ->
25+ { hd = x, tl = repeat x }
26+
27+cycle : a -> [a] -> Stream a
28+cycle x xs = let cycle' ys = case ys of
29+ [] -> mkStream <| \() ->
30+ { hd = x
31+ , tl = cycle' xs }
32+ (y :: ys) -> mkStream <| \() ->
33+ { hd = y
34+ , tl = cycle' ys }
35+ in cycle' []
36+
37+map : (a -> b) -> Stream a -> Stream b
38+map f xs = mkStream <| \() ->
39+ { hd = f (hd xs)
40+ , tl = map f (tl xs)
41+ }
42+
43+apply : Stream (a -> b) -> Stream a -> Stream b
44+apply fs xs = zipWith (<|) fs xs
45+
46+zip : Stream a -> Stream b -> Stream (a, b)
47+zip = zipWith (\x y -> (x,y))
48+
49+zipWith : (a -> b -> c) -> Stream a -> Stream b -> Stream c
50+zipWith f xs ys = mkStream <| \() ->
51+ { hd = f (hd xs) (hd ys)
52+ , tl = zipWith f (tl xs) (tl ys)
53+ }
54+
55+iterate : (a -> a) -> a -> Stream a
56+iterate f x = mkStream <| \() ->
57+ { hd = x
58+ , tl = map f (iterate f x)
59+ }
60+
61+take : Int -> Stream a -> [a]
62+take n xs = case n of
63+ 0 -> []
64+ n -> hd xs :: take (n - 1) (tl xs)
65+
66+observeWhen : Stream a -> Signal b -> Signal a
67+observeWhen str sig = let tls = foldp (\_ -> tl) str sig in
68+ hd <~ tls