【问题标题】:Get specific key and the rest of map with Pattern Matching in Elixir使用 Elixir 中的模式匹配获取特定键和映射的其余部分
【发布时间】:2018-06-06 00:06:48
【问题描述】:

我试图通过模式匹配获取一个元素和地图的其余部分,但我只得到编译错误。

我想出了这个:

%{“One” => one | tail} = %{“One" => 1, "Three" => 3, "Two" => 2}

但是我得到了编译错误,说它是预期的键值对。

我想要实现的行为是:

%{“One” => one | tail} = %{“One" => 1, "Three" => 3, "Two" => 2}
one = 1
tail = %{"Three" => 3, "Two" => 2}

在长生不老药中,有办法实现吗?

【问题讨论】:

  • 很确定没有这样的语法,但如果你只想删除一个键,你可以使用Map.pop/3:Map.pop(%{a: 1, b: 2}, :a) #=> {1, %{b: 2}}
  • 像魅力一样工作。谢谢

标签: dictionary pattern-matching elixir


【解决方案1】:

从 1.6 版开始,Elixir 中没有这方面的语法,但如果您只想一次从映射中删除一个值,您可以使用 Map.pop/2

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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2017-11-02
    • 1970-01-01
    • 2014-07-04
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多