"Make" notation in Elixir and Haskell
I use the "do / end" notation in the elixir more or less than the required block separators. (In other words, do
similar to {
a C-like language, end
similar to }
).
Is this an accurate description of what is happening? Or is it more like Haskell notation do
, which builds syntactic sugar for a monad that allows imperative encoding?
source to share
Yes and no. do
/ end
is a syntactic convenience for keyword lists.
You probably wrote if expressions before. What one might expect to see is like
if predicate do
true_branch
else
false_branch
end
This can also be written using keyword lists. The next one is the same.
if predicate, do: true_branch, else: false_branch
Using the do
/ notation end
allows us to remove verbosity when writing blocks of code. The next two if equivelent statements
if predicate do
a = foo()
bar(a)
end
if predicate, do: (
a = foo()
bar(a)
)
This is the same for defining functions. the macro def/2
also uses a list of keywords. This means that you can define a function like
def foo, do: 5
You can read more about this in the manual.
source to share