在 Elixir 中,是否有一种 shorthand 方法来访问 shorthand 匿名函数符号中的元组项?
In Elixir, is there a shorthand way to access tuple items inside shorthand anonymous function notation?
我遇到的最常见的情况是地图。这是完整的匿名符号:
Enum.sort(some_map, fn {k1,_v1}, {k2,_v2} -> k1 <= k2 end)
这里是shorthand:
Enum.sort(some_map, &( elem(&1,0) <= elem(&2,0) ))
Scala 有 this nice nifty notation for tuple items by index. Does Elixir have something similar or are we stuck using Kernel.elem/2 ?
访问元组的选项是 Kernel.elem/2
, Access.elem/2
and pattern matching. However, the Enum.sort_by/3
函数比 Enum.sort/2
更简洁。
Enum.sort_by(map, &elem(&1, 1)) # Kernel.elem/2
Enum.sort_by(map, fn {key, _value} -> key end) # pattern matcing
如果您不介意地图值,那还可以更短。
map |> Map.keys() |> Enum.sort()
Is there a shorthand way to access tuple items inside shorthand anonymous function notation?
没有
Are we stuck using Kernel.elem/2 ?
是的。
这是我目前使用的解决方案:实现一个运算符。
def tuple ~> index, do: elem(tuple, index)
然后你可以很容易地使用 x~>n 访问并制作超级紧凑的代码,如下所示:
data = [{["root", "dir1"], 100}, {["root", "dir2"], 200}]
data |> Enum.map(& {Enum.join(&1~>0, "."), &1~>1}) |> Map.new
我遇到的最常见的情况是地图。这是完整的匿名符号:
Enum.sort(some_map, fn {k1,_v1}, {k2,_v2} -> k1 <= k2 end)
这里是shorthand:
Enum.sort(some_map, &( elem(&1,0) <= elem(&2,0) ))
Scala 有 this nice nifty notation for tuple items by index. Does Elixir have something similar or are we stuck using Kernel.elem/2 ?
访问元组的选项是 Kernel.elem/2
, Access.elem/2
and pattern matching. However, the Enum.sort_by/3
函数比 Enum.sort/2
更简洁。
Enum.sort_by(map, &elem(&1, 1)) # Kernel.elem/2
Enum.sort_by(map, fn {key, _value} -> key end) # pattern matcing
如果您不介意地图值,那还可以更短。
map |> Map.keys() |> Enum.sort()
Is there a shorthand way to access tuple items inside shorthand anonymous function notation?
没有
Are we stuck using Kernel.elem/2 ?
是的。
这是我目前使用的解决方案:实现一个运算符。
def tuple ~> index, do: elem(tuple, index)
然后你可以很容易地使用 x~>n 访问并制作超级紧凑的代码,如下所示:
data = [{["root", "dir1"], 100}, {["root", "dir2"], 200}]
data |> Enum.map(& {Enum.join(&1~>0, "."), &1~>1}) |> Map.new