Kofi A. Asare

Aspiring Software Engineer

github email
Named Function Outside Of A Module In Elixir
Nov 20, 2018
One minute read

Sometimes, In a dynamic typed language(interactive), you quickly want to group instructions to acheive a behaviour and

repeated use i.e function.

E.g: A function to find the sum of a list of numbers can be implemented so.

Ruby

#irb
def sum(list_of_numbers)
  list_of_numbers.reduce(:+)
end

sum [1,2,3,4,5] #=> 15

Javascript

//node repl
function sum(listOfNumbers){
    return listOfNumbers.reduce((acc = 0, n) => acc + n)
}

sum([1,2,3,4,5]) //=> 15

Elixir

Such flexibility isn’t quite the case in elixir. Demostrated above, elixir simply doesn’t allow defining and calling named

functions outside of a module.

#iex
def sum(list_of_numbers) do
  Enum.reduce(list_of_numbers, fn(a, n) -> a + n end)
end

sum [1,2,3,4,5] #=>
** (ArgumentError) cannot invoke def/2 outside module
(elixir) lib/kernel.ex:5212: Kernel.assert_module_scope/3
(elixir) lib/kernel.ex:3972: Kernel.define/4
(elixir) expanding macro: Kernel.def/2
iex:1: (file)

Aaah!

The simple answer is that You can't!.

Why ?

This is because, the hot code swapping feature in elixir relies on having a module as the code container.

Workaround ๐Ÿ™

However, this can be made possible with an anonymous function

#iex
sum = fn(list) -> Enum.reduce(list, &(&1 + &2)) end

sum.([1,2,3,4,5]) |> IO.puts #=> 15 ๐Ÿ‘


All Posts