2

Using Elixir V1.1.1 on OS X I am having problems getting my head around the Elixir function definition syntax.

Given a function definition:

def foobar(arg1, arg2), do: <<something>> end

It seems that in some cases the comma after the parenthesis is required, other times it is not. Likewise the colon after the 'do' and likewise the closing 'end'. I am sure I am vastly over-complicating the situation, but this seems like a weird setup for a programming language.

Under what circumstances are these elements required/optional?

1 Answer 1

10

You've combined two forms of method definition there - the shorter one-line syntax and the longer do/end syntax.

If you have a one-line method, you can write like the following:

def foobar(foo, bar), do: baz

Note the comma, and no end.

If you have a multi-line method, the syntax is slightly different:

def foobar(foo, bar) do
  foo
  bar
end

Note no comma and the placement of the end.

Both types are described here: http://elixir-lang.org/getting-started/modules.html#named-functions (note the long form for Math.zero?/1, and the shorter form under the 'Function capturing' heading)

4
  • It's a shame that the Elixir syntax seems to be almost completely specified by example, rather than by using a formal syntax definition language. Oh for a bit of BNF, or even Railroad Normal Form :-)
    – Andy
    Nov 29, 2015 at 19:43
  • @Andy It's open source. I'm sure they would welcome a document spelling out the BNF for the syntax. Nov 30, 2015 at 0:58
  • A very good point. I've got the Xmas break coming up, maybe I'll take a stab at one.
    – Andy
    Nov 30, 2015 at 7:39
  • The "end" is completely unnecessary in the functional context, try to clean them and read again the code, really more clean and beautiful.
    – Henry H.
    Apr 7, 2016 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.