在 Erlang 中是否有一种惯用的方式来排序函数子句?
对于子句顺序不重要的函数,是基本情况最后:
all(Pred, [Head|Tail]) ->
case Pred(Head) of
true -> all(Pred, Tail);
false -> false
end;
all(Pred, []) when is_function(Pred, 1) -> true.
还是基本情况先:
all(Pred, []) when is_function(Pred, 1) -> true;
all(Pred, [Head|Tail]) ->
case Pred(Head) of
true -> all(Pred, Tail);
false -> false
end.
从标准库中的源代码来看,似乎约定是基本情况最后。这是首选风格吗?这是有原因的,还是事情就是这样?
For functions where the ordering of the clauses is unimportant, is it base case last:
all(Pred, [Head|Tail]) ->
case Pred(Head) of
true -> all(Pred, Tail);
false -> false
end;
all(Pred, []) when is_function(Pred, 1) -> true.
Or base case first:
all(Pred, []) when is_function(Pred, 1) -> true;
all(Pred, [Head|Tail]) ->
case Pred(Head) of
true -> all(Pred, Tail);
false -> false
end.
From looking at the source code in the standard library, it seems the convention is base case last. Is that the preferred style? Is there a reason for it, or is it just the way it is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只有第二种情况才有效,因为情况是按顺序匹配的。
由于整数 0 能够匹配模式 N,因此如果它在后面,则永远不会到达常量 0 子句。
在编写函数子句、case 子句或任何其他此类潜在匹配序列时,您应该考虑模式匹配的有序方面。
Only the second case will work, as cases are matched in order.
Since the integer 0 is able to match the pattern N, the constant 0 clause would never be reached if it came after.
It is that ordered aspect of pattern-matching which you should think about when writing function clauses, case clauses, or any other such sequence of potential matches.
子句的排序方式具有语义意义。由于模式是按顺序尝试的。
我倾向于将基本案例放在第一位,因为我认为这使其更具可读性。在阅读递归部分时已经了解基本情况。
有时我感觉有些代码将最常见的模式放在第一位,以避免最常见的情况必须测试它不太可能匹配的模式。
It has semantic meaning how the clauses are ordered. Since patterns are attempted in sequential order.
I tend to put base-cases first since I think it makes it more readable. To already know the base cases when reading the recursive part.
Sometimes I get the feeling that some code have put the most common pattern first, to save the most common case from having to test patterns that it will not likely match.
对于
[|]
和[]
我总是将基本情况放在前面,然后将零情况放在最后,就像您的第一种情况一样。我认为这更清晰、更自然。这样做的一个原因可能是它更类似于更一般的模式匹配,您首先有更具体的情况以便捕获它们;这里的[]
就像更具体的情况。不过只是猜测。With
[|]
and[]
I always put the base case(s) first, and the nil case(s) last, as in your first case. I think this much clearer and more natural. One reason for doing the opposite may be that it more resembles the more general pattern matching where you have the more specific cases first so as to catch them; here[]
would be like the more specific case. Just guessing though.