Last active
December 17, 2015 12:59
-
-
Save rsslldnphy/5613903 to your computer and use it in GitHub Desktop.
Basic implementation of infinite series in Erlang, take, filter and nth.
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(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