[英]What's the meaning of "!", "?", "_", and "." syntax in elixir
I need help regarding understanding the following syntaxes in elixir !
我需要有关理解 elixir 中以下语法的帮助!
, ?
, ?
, _
, and .
, _
, 和.
. . What's those syntaxes role in elixir's function?这些语法在 elixir 功能中的作用是什么? For example Repo.get!
例如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?和_
为任何或可变参数?
!
- 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)
. - 正如您提到的,用于调用匿名函数,但也用于访问模块函数,例如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!一个很好的例子是Enum.fetch! (It also has a same Enum.fetch which does not raise exception).Finds the element at the given index (zero-based). (它也有一个相同的Enum.fetch不会引发异常)。在给定的索引处查找元素(从零开始)。 Raises OutOfBoundsError if the given position is outside the range of the collection.如果给定位置超出集合范围,则引发 OutOfBoundsError。
? ? - Used to show that the function will return a boolean value, either true or false. - 用于表明函数将返回一个布尔值,真或假。 One good example is Enum.any?一个很好的例子是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如果你愿意,你可以在下划线后给一个名字。例如 - _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如果你想将任何数字的基数提高到 0 结果它是 1,所以不管基数是什么
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.