Skip to content

Instantly share code, notes, and snippets.

@rsslldnphy
Last active December 17, 2015 12:59
Show Gist options
  • Save rsslldnphy/5613903 to your computer and use it in GitHub Desktop.
Save rsslldnphy/5613903 to your computer and use it in GitHub Desktop.
Basic implementation of infinite series in Erlang, take, filter and nth.
-module(infinite).
-compile(export_all).
%%% Usage
%
% Ints = infinite:stream(0, fun (X) -> X + 1 end).
%
% % Numbers from 0 to 9
% infinite:take(Ints, 10).
%
% % Even numbers only
% infinite:filter(Ints, fun (X) X rem 2 == 0).
%
% % Nth element of a series
% infinite:nth(Ints, 10).
stream (Init, F) ->
fun() -> { Init, stream(F(Init), F) } end.
take (_,0) -> [];
take (S, N) ->
{X,Next} = S(),
[X|take(Next, N - 1)].
filter (S, P) ->
fun () ->
{X,UnfilteredNext} = S(),
FilteredNext = filter(UnfilteredNext, P),
case P(X) of
true -> {X,FilteredNext};
false -> FilteredNext()
end
end.
nth (S, 1) ->
{X,_} = S(), X;
nth (S, N) ->
{_,Next} = S(), nth(Next, N - 1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment