Get specific key and the rest of map with Pattern Matching in Elixir
我正在尝试通过模式匹配来获取一个元素,而其余的地图则只能得到编译错误。
我想到了这个:
1 | %{"One" => one | tail} = %{"One" => 1,"Three" => 3,"Two" => 2} |
但是我收到编译错误,说这是预期的键值对。
我要实现的行为是:
1 2 3 | %{"One" => one | tail} = %{"One" => 1,"Three" => 3,"Two" => 2} one = 1 tail = %{"Three" => 3,"Two" => 2} |
在长生不老药中有一种方法可以实现?
从1.6版开始,Elixir中没有此语法,但是如果您只想一次从地图中删除一个值,则可以使用
1 2 3 4 5 6 | iex(1)> {one, tail} = Map.pop(%{"One" => 1,"Three" => 3,"Two" => 2},"One") {1, %{"Three" => 3,"Two" => 2}} iex(2)> one 1 iex(3)> tail %{"Three" => 3,"Two" => 2} |