Elixir:
Organizing code into functions

How to:

Let’s whip up a simple Elixir function to capitalize words:

defmodule StringUtils do
  def capitalize_words(sentence) do
    sentence
    |> String.split()
    |> Enum.map(&String.capitalize/1)
    |> Enum.join(" ")
  end
end

IO.puts StringUtils.capitalize_words("hello elixir world")

Output:

Hello Elixir World

Here, we’ve neatly packaged the word capitalization logic into a function called capitalize_words.

Deep Dive

In Elixir, and the broader Erlang VM ecosystem, functions are first-class citizens, inheriting the philosophy of breaking down problems into smaller, manageable, and isolated pieces. Historically, this functional approach has roots in lambda calculus and Lisps, promoting code as data philosophy.

Alternatives to organizing code can be using macros or processes in Elixir for repetitive or concurrent tasks, respectively. Implementation-wise, Elixir functions can handle pattern matching and receive different arguments (arity), granting them versatility.

See Also