21

I need help regarding understanding the following syntaxes in elixir !, ?, _, and .. What's those syntaxes role in elixir's function? For example Repo.get!.

I'm not sure whether they were just function name, or has a role. Though I know . is for calling anonymous function. And _ for any or variadic?

ardhitama
  • 1,949
  • 2
  • 18
  • 29

2 Answers2

30

! - 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).

bitwalker
  • 9,061
  • 1
  • 35
  • 27
  • 3
    There does exist an important difference between variables that *start with* the `_` (such as `_foobar`) and those that *consist only* of `_` (such as `def foo(_, _bar) do, _bar end`). Attempts to use the `_` result in compile time 'unbound variable' errors. Variables prefixed with an underscore, `_bar`, serve to prevent warnings for unused variables, and will not prevent compilation. Their use only generates a warning: "warning: the underscored variable "_bar" is used after being set. A leading underscore indicates that the value of the variable should be ignored..." – Marc Oct 26 '15 at 14:45
  • is there any reason is_integer doesn't have a question mark ? - https://hexdocs.pm/elixir/Kernel.html#is_integer/1 @Marc – Deepan Prabhu Babu Sep 28 '20 at 21:51
17

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)
timlyo
  • 2,086
  • 1
  • 23
  • 35
coderVishal
  • 8,369
  • 3
  • 35
  • 56