erlang - erlang 中的 cond 样式语句

标签 erlang lisp case

来自 Lisp 背景,Erlang 的 case 语句对我来说似乎有点莫名其妙。我目前正在研究埃拉托色尼筛法问题,试图生成一个数字 N 的主要因子列表。但是我似乎无法迁移 Lisp 中看似简单的 cond 语句相当于 Erlang 中的。

到目前为止,我已经构造了一个 if 语句,类似于我在 Lisp 中处理事情的方式:

prime_factors(N) -> pf_helper(N, [], 2).


pf_helper(M, PL, D) ->

if 

  prime_p(M) == true -> [ M | PL ];

  (prime_p(D) == true) and (M rem D == 0) -> pl_helper(M div D, [ D | PL ], D+1);

  (prime_p(D) == true) and (M rem D /= 0) -> pl_helper(M, PL, D+1);

  prime_p(D) == false -> pl_helper(M, PL, D+1)

end.

我知道这不会编译,因为我只能在我的守卫中调用 BIF。问题是我无法概念化这将如何作为 case 语句运行,因为 case 处理一个参数的条件表达式。如果我在元组中表示三个 pf_helper 参数:

pf_helper(M,PL,D) -> pf_helper({M, PL, D}).

条件表达式对应的case语句中的模式是什么

   prime_p(M) == true 

  (prime_p(D) == true) and (M rem D == 0) 

  (prime_p(D) == true) and (M rem D /= 0)

  prime_p(D) == false 

?

最佳答案

使用一些守卫:

case {prime_p(M), prime_p(D)} of
  {true, _} -> [M|PL];
  {false, true} when (M rem D == 0) -> ...;
  {false, true} when (M rem D /= 0) -> ...;
  {false, false} -> ...
end

我认为 Anthony Ramine 曾经致力于实现 cond

关于erlang - erlang 中的 cond 样式语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21659569/

相关文章:

lisp - 尾调用和尾递归有什么区别?

MySQL View检查数据是否为NULL

mysql - 如何加快 MySQL Select Case 查询速度

linux - Erlang 脚本中的大小写表达式

class - 不同的初始化,Common Lisp

Erlang:创建光盘模式

list - 对 lisp 中的列表列表进行排序

sql - Postgres 截断 CASE 语句列

炫耀它的好处的 Erlang 代码片段?

redis - Erlang:如何在 eredis 中使用二进制 key /数据?