3 ms·
The unsatisfying answer is that elixir inherits this from erlang. I don't have a good answer on why erlang does it though. For functions of different arities,
by giraffe_lady 3y ago
The unsatisfying answer is that elixir inherits this from erlang. I don't have a good answer on why erlang does it though.
For functions of different arities, erlang (and therefor elixir) considers them completely different functions, and requires a declaration for each arity at least.
But then elixir adds optional args which confuses the answer a little. Being able to hard code handling of exceptional constants in a separate body is very useful but like you said it's conceptually the same thing as a pattern match, and not really an answer about why that feature is there.
I've looked a bit before but I haven't come up with anything more compelling than "erlang was kinda off doing its own thing, syntax-wise, and so some of it is just Like That now."
- sodapopcan 3y agoElixir doesn't technically have default arguments, and this isn't such a pedantic distinction since what it has is a macro that defines a whole other function. defmodule Foo do def bar(baz \\ "baz") do baz end end becomes defmodule Foo do def bar do "baz" end def bar(baz) do baz end end Which, as you pointed out, are two completely separate functions.
- giraffe_lady 3y agoAhh that makes so much sense, I feel like I should have guessed something like that was going on. Thanks!
- Jtsummers 3y ago> "erlang was kinda off doing its own thing, syntax-wise, and so some of it is just Like That now." The syntax makes a lot more sense if you go into the history (well-documented) and understand that Erlang's initial implementation was in Prolog and a lot of the syntax can be seen as a consequence of that. As for pattern matching in the function signature instead of forcing dropping to a case expression, it removes a level of useless and noisy indentation and, again, is a lot more like Prolog. Even the use of , and ; as separators in Erlang make sense given that heritage. In Prolog a sequence like this: A, B, C. Can be read as "A and B and C" while: A; B; C. Can be read as "A or B or C". So function bodies using , as a separator and ; between alternatives with . as a terminal follows straight from Prolog.