Skip to content

Instantly share code, notes, and snippets.

@mudphone
Last active August 29, 2015 14:20
Show Gist options
  • Save mudphone/2246ed174fb9915478ff to your computer and use it in GitHub Desktop.
Save mudphone/2246ed174fb9915478ff to your computer and use it in GitHub Desktop.
Elixir Curry... is delicious
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
@voltone
Copy link

voltone commented May 1, 2015

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:

def curry(f) do
  case :erlang.fun_info(f, :arity) do
    {:arity, 0} -> f
    {:arity, n} -> curryize(f, n, [])
  end
end

@mudphone
Copy link
Author

mudphone commented May 2, 2015

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