繁体   English   中英

将具有不同Arity的函数传递给list:Erlang中的map

[英]Passing in a function with different arity to lists:map in Erlang

假设我想使用lists:map遍历整数lists:map并且希望该map返回一个长度相同但只有大于特定值的数字的列表。 这就是我现在可以实现的方式:

f(Min) ->
    List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    lists:map(fun(N) -> max(N, Min) end, List).

我希望可以做到的一个大概想法是:

f(Min) ->
    List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    lists:map(fun erlang:max/2 (Min), List).

有没有办法将arity大于1的函数作为lists:map函数的第一个参数传递?

在这种情况下,您应该使用列表理解或lists:filter

NewList = [N || N <- List, N > Min]

要么

NewList = lists:filter(fun(N) -> N > Min end, List)

但是,如果您真的更喜欢使用lists:map ,则需要考虑在N小于或等于Min时返回某些内容。

f1(N, Min) when N > Min -> N;
f1(N, Min) when N =< Min -> undefined.  % return 'undefined'

myfun(Min, List) -> lists:map(fun(N) -> f1(N, Min) end, List).

如您所见,您可以通过关闭“关闭”具有任意数量的任何功能。

您将最终得到一个列表,其中所有小于N的数字均由undefined替换,然后是大于N

> myfun(5, [1, 2, 4, 6, 7]).
> [undefined, undefined, undefined, 6, 7]

lists:map与值X -> X'映射有关,而不是过滤列表的成员。

我希望保留列表中的所有元素,但是用我可以作为输入的内容替换无效的元素(在此示例中,在Min之下)

使用与Pie'Oh'Pah答案不同的语法:

my_map(Target, Repl, Nums) ->
    lists:map(
        fun(Num) when Num =< Target  -> Repl;
           (Num)                     -> Num
        end,
        Nums
    ).

在外壳中:

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

16> f1:my_map(3, "-", [1, 2, 3, 4, 5]).
["-","-","-",4,5]

17> f1:my_map(
         fun(X) -> 10 end, 
         [a, {b,c}], 
         [100, a, make_ref(), spawn(fun() -> 2 end), 
          {x, 1}, #{a=>1,b=>2}, [1,2,3]
         ]
    ). 
[[a,{b,c}],
 [a,{b,c}],
 [a,{b,c}],
 <0.68.0>,
 {x,1},
 #{a => 1,b => 2},
 [1,2,3]]

暂无
暂无

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

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