elixir – 如何枚举地图以生成结构列表

我是Elxir的新手.

如果我有以下地图

recos = %{"itemScores" => [%{"item" => "i0", "score" => 0.0126078259487225},
%{"item" => "i3", "score" => 0.007569829148848128},
%{"item" => "i4", "score" => 0.007023984270125072},
%{"item" => "i33", "score" => 0.0068045477730524495}]}

(这是地图吧?)

我如何枚举所有itemScores以生成RecommendationItems列表?

defmodule RecommendedItem do
  defstruct [:item, :score]
end 

我想它会以某种方式发票Enum.map(recos [“itemScores”],fn->;),但我不确定.

最佳答案 这段代码应该做你想要的:

defmodule RecommendedItem do
  defstruct item: "", score: 0
end

defmodule Demo do

  defp parse_list([]), do: []

  defp parse_list([%{"item" => i, "score" => s} | tail]) do
    [%RecommendedItem{item: i, score: s} | parse_list(tail) ]
  end

  def create_recommend_list(%{"itemScores" => score_list})  do
    parse_list(score_list)
  end

end

# And this is how you'd call it.

recos = %{"itemScores" => [%{"item" => "i0", "score" => 0.0126078259487225},
%{"item" => "i3", "score" => 0.007569829148848128},
%{"item" => "i4", "score" => 0.007023984270125072},
%{"item" => "i33", "score" => 0.0068045477730524495}]}

l = Demo.create_recommend_list(recos)

# l = [%RecommendedItem{item: "i0", score: 0.0126078259487225},
# %RecommendedItem{item: "i3", score: 0.007569829148848128},
# %RecommendedItem{item: "i4", score: 0.007023984270125072},
# %RecommendedItem{item: "i33", score: 0.0068045477730524495}]

我希望有所帮助.虽然我认为我理解你所问的是什么,但我认为将每个地图转换为结构都不是你想要做的.

点赞