简体   繁体   English

Erlang:解析和汇总列表

[英]Erlang: parsing and summing a list

I have been working on how solve an Erlang program that is to perform distributed address spacing. 我一直在研究如何解决要执行分布式地址间隔的Erlang程序。 I am trying to create a method that takes an associative and commutative operator, as well a list of values, and then returns the answer by applying the operator to the values in the list. 我试图创建一个采用关联和可交换运算符以及值列表的方法,然后通过运算符应用于列表中的值来返回答案。

The following two examples represent what the input/output are supposed to look like. 以下两个示例表示输入/输出的外观。

Example 1 例子1

Input: sum(fun(A,B) -> A+B end, [2,6,7,10,12]

Output: 37

Example 2 例子2

Input: sum(fun (A,B) -> A++B end , ["C", "D", "E"]).

Output: "CDE"

This is the code I have so far, which is just a function that adds the elements in a list. 这是我到目前为止的代码,它只是一个将元素添加到列表中的函数。 How would I change the method to fit the above examples, as well as to produce the correct result? 我将如何更改方法以适合以上示例,并产生正确的结果? Right now, the code just returns the sum. 现在,代码仅返回总和。

-module(sum).
-export([sum/1]).

sum(L) -> 
   sum(L, 0).

sum([H|T], Acc) -> 
   sum(T, H + Acc); 

sum([], Acc) ->
   Acc.

I wanted to try this serially, before attempting a parallelized version. 在尝试并行化版本之前,我想依次尝试一下。 Please know that before posting this, I tried to look for similar coding examples elsewhere that would help answer my question, but I could not find much, which is why I am posting this. 请知道,在发布此内容之前,我尝试在其他地方寻找类似的编码示例以帮助回答我的问题,但是找不到太多,这就是为什么要发布此内容。

How about this: 这个怎么样:

-module(my).
-compile(export_all).

sum(Func, Data, Acc) ->
    lists:foldr(Func, Acc, Data).

In the shell: 在外壳中:

13> c(my).                                              
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

14> my:sum(fun(X, Acc) -> X+Acc end, [2,6,7,10,12], 0). 
37

15> my:sum(fun(X, Acc) -> X++Acc end, ["C", "D", "E"], []). 
"CDE"

The starting value for the Accumulator(Acc) needs to be different depending on the operator. 累加器(Acc)的起始值需要根据操作员而有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM