on master help sign in
Add more Stream functions and start documentation
5bb782aMax New
libraries/Lazy/Stream.elm+39−14
@@ -1,11 +1,24 @@
1−module Lazy.Stream ( hd, tl, mkStream, repeat, cycle
1+module Lazy.Stream ( hd, tl
2+ , mkStream , iterate, repeat, cycle
2− , map, apply, zip, zipWith, iterate
3+ , map, apply, zip, zipWith, scanl
4+ , take, drop, splitAt
3− , take, observeWhen
5+ , observeWhen
4 ) where
6 ) where
5
7
6−{-| Library for Infinite Streams -}
8+{-| Library for Infinite Streams
7
9
10+# Observe
11+@docs hd, tl, observeWhen, take, drop, splitAt
12+
13+# Create
14+@docs mkStream, iterate, repeat, cycle
15+
16+# Transform
17+@docs map, apply, zip, zipWith, scanl
18+
19+-}
20+
8−import Basics ((.), (<|), (-))
21+import Basics ((.), (<|), (-), id, fst, snd)
9import open Lazy
22import open Lazy
10import Signal ((<~), foldp, Signal)
23import Signal ((<~), foldp, Signal)
11
24
@@ -20,9 +33,14 @@ tl (S t) = (run t).tl
20mkStream : (() -> { hd : a, tl : Stream a }) -> Stream a
33mkStream : (() -> { hd : a, tl : Stream a }) -> Stream a
21mkStream = S . thunk
34mkStream = S . thunk
22
35
36+iterate : (a -> a) -> a -> Stream a
37+iterate f x = mkStream <| \() ->
38+ { hd = x
39+ , tl = map f (iterate f x)
40+ }
41+
23repeat : a -> Stream a
42repeat : a -> Stream a
24−repeat x = mkStream <| \() ->
43+repeat x = iterate id x
25− { hd = x, tl = repeat x }
26
44
27cycle : a -> [a] -> Stream a
45cycle : a -> [a] -> Stream a
28cycle x xs = let cycle' ys = case ys of
46cycle x xs = let cycle' ys = case ys of
@@ -52,16 +70,23 @@ zipWith f xs ys = mkStream <| \() ->
52 , tl = zipWith f (tl xs) (tl ys)
70 , tl = zipWith f (tl xs) (tl ys)
53 }
71 }
54
72
55−iterate : (a -> a) -> a -> Stream a
73+scanl : (a -> b -> b) -> b -> Stream a -> Stream b
56−iterate f x = mkStream <| \() ->
74+scanl f init xs = mkStream <| \() ->
57− { hd = x
75+ { hd = init
58− , tl = map f (iterate f x)
76+ , tl = scanl f (f (hd xs) init) (tl xs)
59 }
77 }
60
78
61take : Int -> Stream a -> [a]
79take : Int -> Stream a -> [a]
80+take n xs = fst <| splitAt n xs
81+
82+drop : Int -> Stream a -> Stream a
83+drop n xs = snd <| splitAt n xs
84+
85+splitAt : Int -> Stream a -> ([a], Stream a)
62−take n xs = case n of
86+splitAt n xs = case n of
63− 0 -> []
87+ 0 -> ([], xs)
64− n -> hd xs :: take (n - 1) (tl xs)
88+ n -> let (hds, end) = splitAt (n - 1) (tl xs)
89+ in (hd xs :: hds, end)
65
90
66observeWhen : Stream a -> Signal b -> Signal a
91observeWhen : Stream a -> Signal b -> Signal a
67observeWhen str sig = let tls = foldp (\_ -> tl) str sig in
92observeWhen str sig = let tls = foldp (\_ -> tl) str sig in