0

In python, we can pass a function into another function like the example code below.

def digits(n):
    return list(map(int, str(n)))

def digit_cube(n):
    return list(map(lambda x: x ** 3, digits(n)))

Can the same be done in elixir? If yes, how?

1 Answer 1

7

One can pass anonymous functions

f = fn e -> e * 2 end
Enum.map([1, 2, 3], f)

or capture the existing function with &/1

defmodule M do
  def dbl(e), do: e * 2
  def map_dbl(list) do
    Enum.map(list, &dbl/1)
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

it may be worth mentioning Kernel.apply/3 ?
@Segfault I think it would be more interesting to point out remote function captures and differences between remote function capture and local function capture.
@Hauleth but it would be copy-pasting the documentation I have explicitly linked, wouldn’t it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.