【发布时间】:2017-06-01 01:00:59
【问题描述】:
我正在研究 Erlang 中的简单列表函数来学习语法。 在我实现“交集”之前,一切看起来都与我为这些函数的 Prolog 版本编写的代码非常相似。
我能想到的最干净的解决方案:
myIntersection([],_) -> [];
myIntersection([X|Xs],Ys) ->
UseFirst = myMember(X,Ys),
myIntersection(UseFirst,X,Xs,Ys).
myIntersection(true,X,Xs,Ys) ->
[X|myIntersection(Xs,Ys)];
myIntersection(_,_,Xs,Ys) ->
myIntersection(Xs,Ys).
对我来说,这感觉有点像 hack。有没有更规范的方法来处理这个问题?我所说的“规范”是指真正符合 Erlang 设计精神的实现。
注意:这个问题的本质是用户定义的谓词函数的条件处理。我不是要求有人将我指向一个库函数。谢谢!
【问题讨论】:
-
我会使用
if(或case):stackoverflow.com/a/4330106/320615。例如。if myMember(X, Ys) -> [X|myIntersection(Xs,Ys)]; .... -
嗯....我认为我们应该避免使用 if 语句——甚至是 case 语句。我想我听过 Francesco Cesarini 在视频中说他帮助 初学者 将 case 语句转换为函数子句。这是风格指南必须说的:github.com/inaka/…。这是乔·阿姆斯特朗(Joe Armstrong)关于此事的有趣读物:erlang.org/pipermail/erlang-questions/2009-December/048101.html
-
@7stud。感谢您的链接。您的评论是唯一明确回答我的问题的评论。由于您仅将其包含在评论中,因此我写了一个引用您的评论的答案。
标签: erlang