Skip to content

Instantly share code, notes, and snippets.

@kylethebaker
Created July 16, 2017 06:07
Show Gist options
  • Save kylethebaker/ba3882354c68a46baf939c4cfbfd62c6 to your computer and use it in GitHub Desktop.
Save kylethebaker/ba3882354c68a46baf939c4cfbfd62c6 to your computer and use it in GitHub Desktop.
Week 3 - Functions as Results
-module(returning_funs).
-compile(export_all).
-type unary() :: fun((Term) -> Term).
% composes a function onto another F(G(X))
-spec compose(unary(), unary()) -> unary().
compose(F, G) ->
fun (X) -> F(G(X)) end.
% composes a list of functions onto each other F(G(...N(X)))
-spec compose_many([unary()]) -> unary().
compose_many(Fs) ->
lists:foldl(fun compose/2, fun identity/1, Fs).
% applies the function twice F(F(X))
-spec twice(unary(), Term) -> Term.
twice(F, X) ->
F2 = compose_many([F, F]),
F2(X).
% returns a function
-spec iterate(pos_integer()) -> unary().
iterate(0) ->
fun identity/1;
iterate(N) ->
fun (F) -> compose_many([F || _ <- lists:seq(1, N)]) end.
% applies a function N times to a value
-spec apply_many(unary(), Term, pos_integer()) -> Term.
apply_many(F, X, N) ->
RepeatedFn = iterate(N),
G = RepeatedFn(F),
G(X).
% identity fn for arity 1
-spec identity(Term) -> Term.
identity(X) -> X.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment