同时将函数应用于Erlang中元组中的每个元素

时间:2015-06-23 19:07:28

标签: concurrency erlang tuples

我有一个元组Class.getDeclaredMethod

我还有一个函数int

//Find the method foo(int)
Method theMethod = theClass.getDeclaredMethod("foo", int.class);

我想将此函数应用于元组中的每个元素,因此我得到结果

{apple, pear, orange, banana}

因为所有功能make_juice/1 make_juice(apple) -> apple_juice(); make_juice(pear) -> pear_juice(); make_juice(orange) -> orange_juice(); make_juice(banana) -> banana_juice(). {apple_juice, pear_juice, orange_juice, banana_juice}apple_juice/0都可能意外失败。我想申请我不希望它中断我的结果。

我想同时将该函数应用于元素。在任何失败的情况下,我仍然会得到部分结果:

pear_juice/0

最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码并行执行映射,同时如果有异常则将结果替换为失败

-module(juice).
-compile(export_all).

make_juice(apple) ->
    apple_juice;
make_juice(pear) ->
    pear_juice;
make_juice(orange) ->
    orange_juice;
make_juice(banana) ->
    0/0.

pmap(Function, List) ->    
    S = self(),
    Pids = lists:map(fun(El) ->
                 spawn(fun() ->
                       execute(S, Function, El) end) 
             end, 
             List),
    gather(Pids).

execute(Recv, Function, Element) ->
    Recv ! {self(), Function(Element)}.

gather([]) ->
    [];
gather([H|T]) ->
    receive
    {H, Ret} ->
        [Ret|gather(T)]
    end.



test() ->
    Elements = [apple, banana, pear, orange],
    pmap(fun(X) -> 
         try make_juice(X) of
             Result -> Result
         catch
             _:_ ->
             fail
         end
     end, Elements).

和测试:

rorra-air:~/erlang > erl
Erlang/OTP 17 [erts-6.4] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V6.4  (abort with ^G)
1> c(juice).
juice.erl:11: Warning: this expression will fail with a 'badarith' exception
{ok,juice}
2> juice:test().
[apple_juice,fail,pear_juice,orange_juice]
3>