在 Erlang 中是否有一种惯用的方式来排序函数子句?

发布于 2024-08-11 20:16:40 字数 480 浏览 1 评论 0原文

对于子句顺序不重要的函数,是基本情况最后:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

煮茶煮酒煮时光 2024-08-18 20:16:40

只有第二种情况才有效,因为情况是按顺序匹配的。

由于整数 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.

神爱温柔 2024-08-18 20:16:40

子句的排序方式具有语义意义。由于模式是按顺序尝试的。

我倾向于将基本案例放在第一位,因为我认为这使其更具可读性。在阅读递归部分时已经了解基本情况。

有时我感觉有些代码将最常见的模式放在第一位,以避免最常见的情况必须测试它不太可能匹配的模式。

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.

血之狂魔 2024-08-18 20:16:40

对于 [|][] 我总是将基本情况放在前面,然后将零情况放在最后,就像您的第一种情况一样。我认为这更清晰、更自然。这样做的一个原因可能是它更类似于更一般的模式匹配,您首先有更具体的情况以便捕获它们;这里的 [] 就像更具体的情况。不过只是猜测。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文