Skip to content

Instantly share code, notes, and snippets.

@calebsmith
Created February 6, 2015 14:01
Show Gist options
  • Save calebsmith/750d599bb811913999e9 to your computer and use it in GitHub Desktop.
Save calebsmith/750d599bb811913999e9 to your computer and use it in GitHub Desktop.
Playing with SKI and Y combinators in Erlang
-module(funs).
%%% SKI combinators
i(X) -> X.
k(X) ->
fun(F) -> X end.
s(F) ->
fun(G) ->
fun(X) ->
(F(X))(G(X))
end
end.
%%% Y combinator
y(F) ->
F (fun (X) -> (y (F)) (X) end).
memoize (F) ->
fun (X) ->
Table = ets:new (?MODULE, [ private ]),
Result = (y (memoize (Table, F))) (X),
ets:delete (Table),
Result
end.
memoize (Table, F) ->
fun(B) ->
fun(C) ->
case ets:lookup(Table, C) of
[] ->
Result = (F (B)) (C),
ets:insert(Table, {C, Result}),
Result;
[{C, Result}] ->
Result
end
end
end.
fibimpl(F) ->
fun (0) -> 1;
(1) -> 1;
(N) when N > 1 -> F (N - 1) + F (N - 2)
end.
factorialimpl(F) ->
fun (0) -> 1;
(1) -> 1;
(N) when N > 1 -> N * F (N - 1)
end.
superfactorialimpl(F) ->
fun (0) -> 1;
(1) -> 1;
(N) when N > 1 -> factorial(N) * F (N - 1)
end.
hyperfactorialimpl(F) ->
fun (0) -> 1;
(1) -> 1;
(N) when N > 1 -> trunc(math:pow(N, N)) * F (N - 1)
end.
fib(N) -> (memoize (fun fibimpl/1)) (N).
factorial(N) -> (memoize (fun factorialimpl/1)) (N).
superfactorial(N) -> (memoize (fun superfactorialimpl/1)) (N).
hyperfactorial(N) -> (memoize (fun hyperfactorialimpl/1)) (N).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment