Skip to content

Instantly share code, notes, and snippets.

@macintux
Created January 11, 2017 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macintux/f19e841464f051a17c339c29cb37bf44 to your computer and use it in GitHub Desktop.
Save macintux/f19e841464f051a17c339c29cb37bf44 to your computer and use it in GitHub Desktop.
Implement in Erlang the lazy evaluation/streaming approach taught by Nathan Dotz at CodeMash 2017.
-module(thunk).
-compile(export_all).
%% > thunk:take(3, thunk:forever_zero()).
%% [0,0,0]
%% > thunk:take(3, thunk:fib()).
%% [1,1,2]
%% > thunk:take(18, thunk:fib()).
%% [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584]
take(0, _Stream) ->
[];
take(N, Stream) ->
[hd(Stream())|take(N-1, (tl(Stream())))].
forever_zero() ->
fun() -> [0 | forever_zero()] end.
fib() ->
F = fun Fib(A, B) ->
fun() ->
[A | Fib(B, A+B)]
end
end,
F(1, 1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment