Super Sexy Swinging Elixir Function Definitions
Add sugar to a basic function definition until it looks like what you’re used to.
def(hi, [{ :do, "ma" }])
Keyword lists have a shorthand syntax.
- def(hi, [{ :do, "ma" }])
+ def(hi, [do: "ma"])
You can even omit the brackets.
- def(hi, [do: "ma"])
+ def(hi, do: "ma")
You can omit parens for function calls, too.
- def(hi, do: "ma")
+ def hi, do: "ma"
Add an argument.
- def hi, do: "ma"
+ def hi(mark), do: "ma#{mark}"
Add a default value.
- def hi, do: "ma"
+ def hi(mark \\ "!"), do: "ma#{mark}"
Add optional parens around the do:
expression.
- def hi(mark \\ "!"), do: "ma#{mark}"
+ def hi(mark \\ "!"), do: ("ma#{mark}")
We can have many expressions evaluated in do:
.
- def hi(mark \\ "!"), do: ("ma#{mark}")
+ def hi(mark \\ "!"), do: (
+ 1
+ 2
+ 3
+ "ma#{mark}"
+ )
Instead of wrapping multiple do: expressions in parens, use a do/end block.
- def hi(mark \\ "!"), do: (
+ def hi(mark \\ "!") do
1
2
3
"ma#{mark}"
- )
+ end