我是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->;)发票,但我不确定
答案 0 :(得分:1)
感谢@ zaboco的评论指出struct/2
无法正常工作,因为你的地图有字符串而不是原子键。
这是在调用Enum.map
:
Enum.map(recos["itemScores"], fn %{"item" => item, "score" => score} -> %RecommendedItem{item: item, score: score} end)
这次我测试并验证了代码。
答案 1 :(得分:0)
此代码应该按您的要求执行:
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}]
我希望有所帮助。虽然我认为我明白你在问什么,但我不认为将每个地图转换成结构就是你想要做的。