【问题标题】:Enumerating an Elixir HashDict structure枚举 Elixir HashDict 结构
【发布时间】:2015-12-03 12:25:55
【问题描述】:

我是 Elixir 的新手,我正在尝试编写一个 GenServer,它将键、值对存储在 HashDict 中。存储复合键和值很好。这是代码:

  #Initialise the HashDict GenServer.start_link
  def init(:ok) do
    {:ok, HashDict.new}
  end

  #Implement the server call back for GenServer.cast 
  def handle_cast({:add, event}, dict) do
    {foo, bar, baz, qux} = event

    key = %{key1: foo, key2: bar}
    value = %{val1: baz, val2: qux}

    {:noreply, HashDict.put(dict, key, value) }
  end

一切都好。但是我无法实现我想要的 handle_call 行为。所以在这里我想:

  1. 对于给定的key1 值,检索HashDict 中所有对应的value 条目。这意味着忽略 key2 的值(有点像全选)。
  2. 返回所有 val2s 后,将它们全部相加(假设它们是整数,忽略 val1)得出总和。

所以我已经走到了这一步:

def handle_call({:get, getKey}, _from, dict) do
  key = %{key1: getKey, key2: _}
  {:reply, HashDict.fetch(dict, key), dict}
end

这不起作用,因为无法在 _ 上进行模式匹配。大概我会在地图上使用某种Enumeration 来实现我的第二个目标:

Enum.map(mymap, fn {k, v} -> v end)|> Enum.sum{}

但我似乎无法完全破解语法来实现我的两个目标。感谢您的帮助!

【问题讨论】:

    标签: dictionary enums elixir


    【解决方案1】:

    如果我正确理解了您的问题,以下应该可以完成您想要做的事情:

    def handle_call({:get, getKey}, _from, dict) do
      sum = Enum.reduce(dict, 0, fn
        ({%{key1: key1}, %{val2: val2}}, acc)
            when key1 === getKey
            and is_integer(val2) ->
          val2 + acc
        (_, acc) ->
          acc
      end)
      {:reply, sum, dict}
    end
    

    有关更多信息,请参阅Enum.reduce/3 的文档。

    【讨论】:

    • 是的,这是一种享受。当我尝试以下操作时(我认为与您上面的内容相同......),它没有用,有什么想法吗? myList = Enum.filter(dict, fn ({{key1,key2},{val1,val2}}) -> key1 == getKey end){:reply, List.foldr(myList,0, fn ({{key1,key2},{val1,val2}},acc) -> val2 + acc end), dict}
    • 在您的问题中,您对键和值都使用了Map。所以myList = Enum.filter(dict, fn ({%{key1: key1}, _}) -> key1 === getKey end){:reply, List.foldr(myList, 0, fn ({_, %{val2: val2}}, acc) -> val2 + acc end), dict} 会起作用。您最好使用MapList 而不是HashDict。以下是一些示例:gist.github.com/potatosalad/ba4a556c5be5768825f4
    • 啊哈!说得通。这很棒。谢谢!
    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2016-11-26
    相关资源
    最近更新 更多