Functions in Elixir
Functions are central in Elixir. We’ll learn about functions with a few different examples.
To run this Elixir code, you would typically save it in a file (e.g., functions.exs
) and then use the elixir
command:
In Elixir, functions are defined within modules. The defmodule
keyword is used to define a module, and def
is used to define a function within that module.
Elixir is a functional programming language, so functions are first-class citizens. It has some key differences from imperative languages:
- Functions automatically return the value of their last expression.
- There’s no need to specify parameter or return types - Elixir is dynamically typed.
- Function calls on modules use dot notation (e.g.,
Example.plus(1, 2)
).
Elixir also supports many other powerful features related to functions, such as pattern matching, guards, and default arguments, which we’ll explore in later examples.