Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Do" notation in Elixir and Haskell

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?

like image 536
Mark Karavan Avatar asked Feb 05 '23 11:02

Mark Karavan


1 Answers

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.

like image 187
Justin Wood Avatar answered Mar 21 '23 03:03

Justin Wood