Erlang:是否可以将最小函数编写为列表折叠?
给定一个函数:
min(A, B) when A =< B -> A;
min(_A, B) -> B.
我可以在函数 foldl
中以类似的方式使用它吗:
lists:foldl(fun min/2, 0, [1,2,3,4,5,6,7,8,9,10])
我相信这是不可能的,因为我必须设置一个初始值,该值将与其余的进行比较列表,例如我能想到没有恒等函数。我说得对吗?
语法是用 Erlang 编写的,但对于非 Erlang 程序员也应该可读。
Given a function:
min(A, B) when A =< B -> A;
min(_A, B) -> B.
can I use this in the function foldl
in a similar fashion to this:
lists:foldl(fun min/2, 0, [1,2,3,4,5,6,7,8,9,10])
I believe it is not possible, because I have to set an initial value that will be compared to the rest of the list, e. g. there is no identity function that I can think of. Am I right?
Syntax is written in Erlang, but should be readable for non Erlang programmers, too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
undefined
作为初始状态应该可以解决问题。对于空列表返回undefined
,这作为一个 API 来说是很好的。如果您希望它在空列表上崩溃,请改用此函数头:
Using
undefined
as the initial state should do the trick. Returnsundefined
for an empty list, which is kind of nice as an API.If you want it to crash on an empty list, use this function header instead:
使空列表上的程序崩溃,推荐的方法是“让它崩溃”,而不是防御性编程。
Crashes a program on an empty list, a recommended approach "let it crash" as opposed to defensive programming.
Adam Lindberg 提出使用
undefined
作为初始值的缺点是,它会为以原子为成员的列表生成奇怪的结果。 Erlang 对所有对象具有全局排序,因此 min 函数的一个很好的属性是可用于所有类型。我认为在空列表上崩溃更合理。不同之处在于,客户端必须担心大小写,而不是担心得到
undefined
结果。Adam Lindbergs proposal to use
undefined
as initial value has the disadvantage that it generates weird results for lists that has atoms as members. Erlang has a global ordering of all objects, so a nice property of a min function would be to be usable for all types.I think its more reasonable to crash on an empty list. The difference is that the client has to worry about the case, instead of having to worry about getting a
undefined
as the result.