Last active
May 15, 2026 16:04
-
-
Save LCamel/90ad0f97fa6df6d00be779f70f90be82 to your computer and use it in GitHub Desktop.
Stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| genFib = function* () { | |
| let [curr, next] = [0, 1]; | |
| while (true) { | |
| yield curr; | |
| [curr, next] = [next, curr + next]; | |
| } | |
| }; | |
| fib = genFib(); | |
| while (true) { | |
| console.log(fib.next().value); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Foo where | |
| type Stream a = [a] | |
| nat :: Stream Int | |
| nat = loop 0 where | |
| loop i = i : loop (i + 1) | |
| fib :: Stream Int | |
| fib = loop 0 1 where | |
| loop curr next = curr : loop next (curr + next) | |
| not3 :: Stream Int | |
| not3 = loop 0 where | |
| loop i | |
| | i `mod` 3 == 0 = loop (i + 1) | |
| | otherwise = i : loop (i + 1) | |
| mapS :: (a -> b) -> Stream a -> Stream b | |
| mapS f xs0 = loop xs0 where | |
| loop xs = f (head xs) : loop (tail xs) | |
| infixr 5 \/ | |
| (\/) :: Stream a -> Stream a -> Stream a | |
| xs0 \/ ys0 = loop xs0 ys0 where | |
| loop xs ys = (head xs) : loop ys (tail xs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Foo2 where | |
| type Stream a = [a] | |
| mkStream :: state -> (state -> (a, state)) -> Stream a | |
| mkStream initState f = loop initState where | |
| loop state = | |
| let (v, newState) = f state | |
| in v : loop newState | |
| nat :: Stream Int | |
| nat = mkStream 0 $ \i -> (i, i + 1) | |
| fib :: Stream Int | |
| fib = mkStream (0, 1) $ | |
| \(curr, next) -> (curr, (next, curr + next)) | |
| mapS :: (a -> b) -> Stream a -> Stream b | |
| mapS f xs0 = mkStream xs0 $ | |
| \xs -> (f (head xs), tail xs) | |
| infixr 5 \/ | |
| (\/) :: Stream a -> Stream a -> Stream a | |
| xs0 \/ ys0 = mkStream (xs0, ys0) $ | |
| \(xs, ys) -> (head xs, (ys, tail xs)) | |
| mkStream_ :: state -> (state -> (Maybe a, state)) -> Stream a | |
| mkStream_ initState f = loop initState where | |
| loop state = case f state of | |
| (Nothing, newState) -> loop newState | |
| (Just a, newState) -> a : loop newState | |
| not3 :: Stream Int | |
| not3 = mkStream_ 0 $ | |
| \i -> (if i `mod` 3 == 0 then Nothing else Just i, i + 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment