List coercion (for fun and profit)
Notes
Sometimes, we want our function to take in a list, a single element, or perhaps
even nil
. But the operations inside the body of our function require a list.
Well, I have a trick for you.
In those cases, I like to do list coercion with List.wrap/1
:
iex> List.wrap([1, 3, 4])
[1, 3, 4]
iex> List.wrap(1)
[1]
iex> List.wrap(nil)
[]
Pretty neat, huh?