【问题标题】:Erlang : Finding multiple Max values of a listErlang:查找列表的多个最大值
【发布时间】:2017-07-10 23:18:53
【问题描述】:

首先我对Erlang一无所知,我们是我和一个同事,将couchDB中的Map Reduce从JS重写为Erlang作为测试。

在输入中我们有类似的东西:

{[
    {<<"score">>, {[ {<<"max">>, SCORE_MAX} ]} },
    {<<"points">>, {[ {<<"max">>, POINTS_MAX}, {<<"total">>, POINTS_TOTAL} ]} },
    {<<"time">>, {[ {<<"total">>, TIME_TOTAL} ]} },
    {<<"success">>, SUCCESS},
//etc..
]}

我们想遍历列表[ [score, progress, points ] ] 并输出这个列表的“max(score), max(progress), max(points)”。

到目前为止,我们成功做的唯一一件事是每个我们想要的 max(value) 或 sum(value) 一个循环 例如:

        PROGRESS_MAX = lists:max(lists:map(fun({Value}) ->
            {Progress} = proplists:get_value(<<"progress">>, Value),
            proplists:get_value(<<"max">>, Progress)
        end, Values)),

        LEVEL_MAX = lists:max(lists:map(fun({Value}) ->
            {Level} = proplists:get_value(<<"level">>, Value),
            Max = proplists:get_value(<<"max">>, Level, 0)
        end, Values)),

        POINTS_TOTAL = lists:sum(lists:map(fun({Value}) ->
            {Points} = proplists:get_value(<<"points">>, Value),
            proplists:get_value(<<"total">>, Points)
        end, Values)),

知道如何以更有效的方式做到这一点吗? 因为在这里我们只是为我们想要的每一种值做一个循环(列表:映射)..我们的思维太紧张了,无法进行过程编程和可变变量,所以我们无法找到一种有效的方法..

谢谢

【问题讨论】:

    标签: algorithm list functional-programming erlang


    【解决方案1】:

    更新了答案以反映 cmets

    我冒昧地修改了输入数据以便编译答案。

        InputList = [{[
       {<<"score">>, {[ {<<"max">>, 2} ]} },
       {<<"points">>, {[ {<<"max">>, 3}, {<<"total">>, 7} ]} },
       {<<"time">>, {[ {<<"total">>, 4} ]} },
       {<<"success">>, 9}
       ]},
     {[
       {<<"score">>, {[ {<<"max">>, 2} ]} },
       {<<"points">>, {[ {<<"max">>, 3}, {<<"total">>, 7} ]} },
       {<<"time">>, {[ {<<"total">>, 4} ]} },
       {<<"success">>, 9}
       ]}],
    lists:foldl(fun({L0}, Dict0)->
                        lists:foldl(fun({E, {L}}, Dict1)->
                                            Max=proplists:get_value(<<"max">>, L, 0),
                                            dict:update(E, fun(OldValue)-> OldValue + Max end, Max, Dict1);
                                       (_, Dict1) -> Dict1 
                                    end, Dict0, L0)
               end, dict:new(), InputList).
    

    【讨论】:

    • 我认为我没有正确暴露问题,因为我们在沙发视图中。但输入是头部示例的数组。所以,我们需要“最大值中的最大值”。在工作中,我们继续前进并拆分为更多视图以简化所有内容(erlang 语法等),但为了了解如何使用纯 Erlang 完成它,我将在稍后更新..(本周结束时我可能会有时间在 couchdb 之外设置问题)无论如何感谢您的尝试:)
    • 我已经更新了答案以匹配您的 cmets。
    • 太棒了!这正是我希望我们可以在 erlang 中做的事情。下次我有类似的东西时会尝试它(dict & dict:update 对我们来说是很棒的)
    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2016-10-04
    • 2018-09-13
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多