I have been using "do/end" notation in elixir more-or-less like imperative block delimiters. (In other words, do is like { in a C-like language, end is like }).
Is this an accurate description of what's going on? Or is it more like the Haskell do notation, which constructs syntactic sugar for a monad that allows for imperative-like coding?
Yes and no. do/end is a syntactic convenience for keyword lists.
You have probably written if expressions before. What someone may expect to see is something like
if predicate do
true_branch
else
false_branch
end
This can also be written using keyword lists. The following is the exact same.
if predicate, do: true_branch, else: false_branch
Using the do/end notation allows us to remove verbosity when writing blocks of code. The following two if expressions are equivelent
if predicate do
a = foo()
bar(a)
end
if predicate, do: (
a = foo()
bar(a)
)
This is the same for defining functions. the def/2 macro uses a keyword list as well. Meaning you can define a function like the following
def foo, do: 5
You can read more about this in the getting started guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With