I am still exploring Elixir anonymous function, let’s move on to another interesting feature. Like javascript or functional programming language, in Elixir we can writes function that takes one or more functions as an input and or returns a function,

iex(1)> passed_func = fn(a) -> a + 3 end
#Function<6.90072148/1 in :erl_eval.expr/5>
iex(2)> apply_func = fn(func_arg, num) -> func_arg.(func_arg.(num)) end
#Function<12.90072148/2 in :erl_eval.expr/5>
iex(3)> apply_func.(passed_func, 7)
We have passed_func which is a function that returns a function, and apply_func which is takes function as an argument. Inside apply_func we apply passed_func twice.

Like Ruby, inside Elixir Enum module has a function called map which has the same purpose, different with Ruby, in Elixir the map function takes two arguments, first is a collection and second is a function.

ruby way:

irb(main):001:0> list = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):002:0>{|el| el * 2}
=> [2, 4, 6, 8, 10]

elixir way

iex(5)> list = [1,2,3,4,5]
[1, 2, 3, 4, 5]
iex(6)> list, fn(el) -> el * 2 end
[2, 4, 6, 8, 10]

The & Shortcut

Again like a Ruby, Elixir has & operator to write short function. The body of the function surrounded by ( and ), and the the placeholders &1, &2, and so on correspond to the first, second, and subsequent parameters of the function.

iex(2)> add = &(&1 + &2)
iex(3)> add.(9, 4)

This shortcut function can be applied in map function:

ruby way

irb(main):009:0> list = %w<a b c d e>
=> ["a", "b", "c", "d", "e"]
=> ["A", "B", "C", "D", "E"]

elixir way

iex(7)> list = ["a", "b", "c", "d", "e"]
["a", "b", "c", "d", "e"]
iex(8)> list, &(String.upcase(&1))
["A", "B", "C", "D", "E"]

Blog Logo

Agung Prasetyo



devblog of @sgt_mactavish

Back to Overview