Erlang 中的保护表达式:使用 "and" 与使用 "comma"

Guard expressions in Erlang: using "and" vs using "comma"

我刚开始学习Erlang,但我不明白为什么这段代码与函数调用不匹配test:sum(3)

-module(test).
-export([sum/1]).

sum(0) -> 0;
sum(N) when is_integer(N) and N>0 -> N + sum(N - 1).

...虽然这样做:

-module(test).
-export([sum/1]).

sum(0) -> 0;
sum(N) when is_integer(N), N>0 -> N + sum(N - 1).

关于这两种不同的方法,我是否遗漏了什么?

这是因为运算符的优先级。

根据 reference 中的定义,运算符 and 出现在 > 之前,因此您在第一个代码片段中实际得到的是:

sum(N) when (is_integer(N) and N)>0 -> N + sum(N - 1).

所以在你的情况下,你正在比较 (true and 3) > 0,这不可能是真的,这就是为什么你的守卫永远不会匹配。

要解决这个问题,你可以这样写你的守卫:

sum(N) when (is_integer(N)) and (N>0) -> N + sum(N - 1).

P.S。 is_integer/1 的括号在这种情况下不是必需的,但这样看起来可能更清楚。