list – 是否可以选择将管道输出插入Elixir函数args的位置?

前端之家收集整理的这篇文章主要介绍了list – 是否可以选择将管道输出插入Elixir函数args的位置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑一下(臭,非惯用)函数,如下所示:

def update_2d(array,inds,val) do
    [first_coord,second_coord] = inds

    new_arr = List.update_at(array,second_coord,fn(y) ->
      List.update_at(Enum.at(array,second_coord),first_coord,fn(x) -> val end) end)
end

函数将包含列表列表,两个索引的列表以及要在索引指定的位置的列表列表中插入的值.

作为制作更多Elixir-ey的第一步,我开始铺设管道:

array 
  |> Enum.at(second_coord) 
  |> List.update_at(first_coord,fn(x) -> val end)

这让我大部分都在那里,但是如何将输出传递到最后一个List.update_at调用的匿名函数?我可以将它嵌入原始调用中,但这似乎放弃了:

List.update_at(array,fn(y) -> 
  array 
  |> Enum.at(second_coord) 
  |> List.update_at(first_coord,fn(x) -> val end) 
end)

解决方法

您可以简单地绑定到变量以捕获第一个结果,然后在第二个List.update_at / 3调用中替换它

def update_2d(array,inds = [first_coord,second_coord],val) do
  updated =
    array
    |> Enum.at(second_coord) 
    |> List.update_at(first_coord,fn(x) -> val end)

    List.update_at(array,fn(x) -> updated end)
end

您也可以使用capture运算符执行此操作:

def update_2d(array,val),do:    
    array
    |> Enum.at(second_coord) 
    |> List.update_at(first_coord,fn(x) -> val end)
    |> (&(List.update_at(array,fn(y) -> &1 end))).()

我发现使用一个更易读的变量,但选项就在那里.

猜你在找的设计模式相关文章