What's the meaning of "!", "?", "_", and "." syntax in elixir

! - Convention for functions which raise exceptions on failure.

? - Convention for functions which return a boolean value

_ - Used to ignore an argument or part of a pattern match expression.

. - As you mentioned is used for calling an anonymous function, but is also used for accessing a module function such as Mod.a(arg).


Firstly ! and ?

They are naming conventions usually applied to the end of function name and are not any special syntax.

! - Will raise an exception if the function encounters an error.

One good example is Enum.fetch!(It also has a same Enum.fetch which does not raise exception).Finds the element at the given index (zero-based). Raises OutOfBoundsError if the given position is outside the range of the collection.

? - Used to show that the function will return a boolean value, either true or false. One good example is Enum.any? that returns true if functions is true for any value, otherwise return false

_ - This will ignore an argument in function or in pattern matching. If you like you can give a name after underscore.Ex - _base

This is commonly used in the end of a tail recursive function. One good example is the power function. If you want to raise any number base to 0 the result it 1, so it really does not matter what base is

defp getPower(_base,0), do: 1

. - Used to access any function inside the module or as you suggested calling an anonymous function

iex(1)> square = fn(number) -> number * number end
iex(2)> square.(4)

Tags:

Elixir