【问题标题】:erlang "illegal guard expression" while using function in Guards在Guards中使用函数时erlang“非法守卫表达式”
【发布时间】:2019-11-22 10:22:43
【问题描述】:

我有以下代码。我正在检查 3 个条件。您可以看到,对于第一个条件,我将xml:get_tag_attr_s(...) 的输出存储在一个变量中,然后在 if 块中使用该变量。我的问题是我收到错误illegal guard expression,如果我尝试像其他两个条件一样在一行中执行上述过程。

另外,我从默认条件中得到variable '_' is unbound。应该是一样的。

有人可以解释一下这个问题吗?

validate_xmpp(Packet) ->
      Type = xml:get_tag_attr_s(list_to_binary("type"), Packet),
      if
          (Type /= <<"chat">> ->
              {error, "Message type is not chat"};
          xml:get_path_s(Packet, [{elem, list_to_binary("body")}, cdata]) /= <<"">> ->
              {error, "No or empty body"};
          exml_query:path(Packet, [{element,<<"received">>},{attr,<<"xmlns">>}]) == <<"urn:xmpp:receipts">> ->
              {error, "delivery-receipts should be ignored"};
          _->
              {ok, xml:get_tag_attr_s(list_to_binary("from"), Packet)}
      end.

【问题讨论】:

标签: erlang


【解决方案1】:

Erlang 只允许这些作为守卫:

欲了解更多信息,请查看http://www.erlang.org/doc/reference_manual/expressions.html#id83606

使用true 代替_。不能在if 中使用_,只能在case 语句中使用,也可以看看docs

【讨论】:

  • 谢谢!我得到的变量 '_' is unbound error 呢?
【解决方案2】:
isPrime(A,B) when B>math:sqrt(A) -> true;

这会导致非法守卫错误。

初读时,守卫似乎包含“术语比较”:

>

还有一个“算术表达式”:

math:sqrt(A)

此外,如果你玩弄代码,你会看到守卫:

B > A+2 

合法的。那么“算术表达式”math:sqrt(A)A+2有什么区别呢?

Erlang docs 将“算术表达式”定义为:`

+   
- 
*
/
div
rem
bnot
band
bor
bxor
bsl
bsr

值得注意的是,math:sqrt() 不在“算术表达式”列表中。因此,math:sqrt(A) 是一个“函数调用”而不是一个“算术表达式”,并且您只能在一个守卫中调用一定数量的函数,即here 列出的“类型测试 BIF”,例如:

is_integer/1
is_float/1
is_binary/1
is_list/1
is_map/1
is_function/1
etc.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2011-03-30
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多