Anonymous functions in Elixir The Right Way

This is not a serious post. If you’re after serious in-depth discussion of serious ideas, you shall find none here. You’ve been warned…

Elixir’s anonymous functions are a little awkward. For example:

iex> numbers = [1,2,3,4,5,6]     
[1, 2, 3, 4, 5, 6]
iex> Enum.map(numbers, &(&1 + 2))
[3, 4, 5, 6, 7, 8]

This &(&1...) thing doesn’t feel right. What if we could have lambda functions like Church intended? Wait no more:

iex> import Lambda
Lambda
iex> numbers = [1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6]
iex> Enum.map(numbers, λ(&1 + 2))
[3, 4, 5, 6, 7, 8]

Where Lambda is defined as:

defmodule Lambda do
  defmacro λ(ast) do
    quote do
      &(unquote(ast))
    end
  end
end

Name’s still free on hex.pm :smile:

PS: I did try this:

def Σ(enum) do
  Enum.sum(enum)
end

which unfortunately fails due to Elixir’s surprisingly correct interpretation of Unicode case rules xD

This is all a little silly, but hopefully people might find it amusing.

7 Likes

/me coughs

def unquote(Σ)(enum) do

^.^

2 Likes