Last active
August 29, 2015 14:20
-
-
Save mudphone/2246ed174fb9915478ff to your computer and use it in GitHub Desktop.
Elixir Curry... is delicious
This file contains 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
defmodule Math do | |
def add(x, y) do | |
x + y | |
end | |
def add(x, y, z) do | |
x + y + z | |
end | |
def div(x, y) do | |
x / y | |
end | |
def div(x, y, z) do | |
x / y / z | |
end | |
end | |
defmodule Curry do | |
def arity(f) when is_function(f), do: arity(f, 0) | |
defp arity(f, n) when is_function(f, n), do: n | |
defp arity(f, n), do: arity(f, n+1) | |
defp curryize(f, 0, args) do | |
apply(f, args) | |
end | |
defp curryize(f, n, args) do | |
fn x -> | |
curryize(f, n-1, args ++ [x]) | |
end | |
end | |
def curry(f) do | |
case n = arity(f) do | |
0 -> f | |
_ -> curryize(f, n, []) | |
end | |
end | |
def curry2(f) do | |
fn a -> | |
fn b -> | |
f.(a, b) | |
end | |
end | |
end | |
end |
Thanks for that! I've added it to a lib where I'm keeping these things...
https://github.com/mudphone/Hoex/blob/master/lib/hoex.ex
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like my recursive solution for finding the arity of a function isn't even necessary. Just came across this:
https://groups.google.com/forum/#!topic/erlang-programming/sU7RtQm9qs0
So you could drop the arity function and write: