Ever been curious about why something is the way it is in Elixir?
Or perhaps the way something works the way it does?
If so then this thread is just for you
Perhaps you’ve had similar queries in the past which have since been answered, if so please add them to this thread to help others who might be wondering the same
This thread is also a great way to test your own understanding - if you think you know an answer to a query please share it (and if you think you can improve on an answer someone else has provided, please do).
We may also use the thread to propose changes or additions to the official Elixir FAQ, so please help us by taking part.
One of the first things I was curious about was why we had to do this in Elixir:
name = "elixir"
String.capitalize(name)
and couldn’t just do this:
name = "elixir"
name.capitalize
The answer was provided by PragDave in his book Programming Elixir; that the syntax is a reminder that we are working with immutable data and that functions don’t modify data, they return completely new versions of it.
/me is saddened by the demise of tuple modules in recent erlang’s, great for passing around data and functions that was not just anonymous functions. ^.^
Erlang does not have a concept of optional arguments, so nothing to pull from there.
= is already used in matchspec’s for function definitions, so cannot use it or it would be ambiguous (def blah(i = 1) would mean is default arg of 1 or only ‘matches’ on a 1, ambiguous).
Ruby has no such construct that I’ve ever seen as \\ either, so my guess is that it is just an unused operator so it was taken for this purpose, especially as it does not require hitting the Shift key to access.
That’s interesting - I didn’t know Erlang doesn’t allow default arguments in functions. That makes me more curious why it’s not the = (as per Ruby) but \\ (as it is in Perl) :101:
Well, I guess the fact that = is used for matching is the reason it’s not used for default parameters, it would. But why \\, I’m just as curious as you are! Maybe it’s inspered from Perl like @vidalraphael said, thank you for that, I didn’t know!
But I catch me doing a lot of this:
def add(a), do: add(a, 1)
def add(a, b), do: a + b
Instead of:
def add(a, b \\ 1), do: a + b
The \\ operator was very confusing to me in the start (I keep doing // instead of \\). I guess that’s why I go with the first option so many times.
Whenever I use a default arg I keep waiting for the compile error. I think it’s because // means comment in a lot of languages, so \\ just feels wrong at the beginning (unless you have a background in Perl ).