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

风流意气都作罢 提交于 2019-12-03 12:27:52

问题


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?


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/32449423/whats-the-meaning-of-and-syntax-in-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!