创建新的保护条款 [英] Create new guard clause
问题描述
中调用任何函数,但是能够做到这样的事情会很好: defmodule Player do
def play_card(player),do:[]
def play_card(player)has_cards(player)球员),做:...
#定义has_cards作为守卫子句?
end
解决方案简短的回答是:你不能。
长的答案是你可以定义宏,只要它们是由有效的守卫表达式组成的,他们就可以在守卫中工作。但这对于复杂的守卫来说并不重要,所以最好避免这种情况,除非你真的必须这样做。
有效的守卫名单可以在入门指南中找到:< a href =http://elixir-lang.org/getting-started/case-cond-and-if.html#expressions-in-guard-clauses> http://elixir-lang.org/getting-started /case-cond-and-if.html#expressions-in-guard-clauses
可以找到一个复杂后卫宏的示例实现在Elixir源文件中: https://github.com/elixir- lang / elixir / blob / 5d34fcdccd20bf38c4f2a13f8adeb78e22b4e74c / lib / elixir / lib / kernel.ex#L1574
In Elixir, how would I go about creating a new guard clause for a function? Obviously, I've seen that you can't just call any function in a when
statement, but it would be nice to be able to do something like this:
defmodule Player do
def play_card(player), do: []
def play_card(player) when has_cards(player), do: ...
# Define has_cards as guard clause?
end
解决方案 The short answer is: you can't.
The long answer is that you can define macros and they will work in guards as long as they are made of valid guards expressions. But that is non-trivial for complex guards so it is better avoided unless you really have to.
The list of valid guards can be found in the getting started guide: http://elixir-lang.org/getting-started/case-cond-and-if.html#expressions-in-guard-clauses
A sample implementation of a "complex" guard macro can be found in Elixir source: https://github.com/elixir-lang/elixir/blob/5d34fcdccd20bf38c4f2a13f8adeb78e22b4e74c/lib/elixir/lib/kernel.ex#L1574
这篇关于创建新的保护条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!