Erlang:是否可以将最小函数编写为列表折叠?

发布于 2024-10-20 02:19:57 字数 341 浏览 7 评论 0原文

给定一个函数:

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

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

发布评论

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

评论(3

无所谓啦 2024-10-27 02:19:57
min(List) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, undefined, List).

使用 undefined 作为初始状态应该可以解决问题。对于空列表返回 undefined,这作为一个 API 来说是很好的。

如果您希望它在空列表上崩溃,请改用此函数头:

min([Head|Rest]) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, Head, Rest).
min(List) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, undefined, List).

Using undefined as the initial state should do the trick. Returns undefined 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:

min([Head|Rest]) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, Head, Rest).
‖放下 2024-10-27 02:19:57
1> List = [42,13,25,3,19,20].
[42,13,25,3,19,20]
2> lists:foldl(fun(X, Y) -> erlang:min(X,Y) end, hd(List), tl(List)).   
3

使空列表上的程序崩溃,推荐的方法是“让它崩溃”,而不是防御性编程。

1> List = [42,13,25,3,19,20].
[42,13,25,3,19,20]
2> lists:foldl(fun(X, Y) -> erlang:min(X,Y) end, hd(List), tl(List)).   
3

Crashes a program on an empty list, a recommended approach "let it crash" as opposed to defensive programming.

梦幻的味道 2024-10-27 02:19:57

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.

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