How to list a map to create a list of structures
I am new to Elxir.
If I have the following card
recos = %{"itemScores" => [%{"item" => "i0", "score" => 0.0126078259487225},
%{"item" => "i3", "score" => 0.007569829148848128},
%{"item" => "i4", "score" => 0.007023984270125072},
%{"item" => "i33", "score" => 0.0068045477730524495}]}
(Is this the map on the right?)
How would I list all ItemScores items to create a list of Recommendations?
defmodule RecommendedItem do
defstruct [:item, :score]
end
I think he is going to invoice Enum.map (recos ["itemScores"], fn->) somehow, but I'm not sure.
This code should do what you want:
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}]
Hope this helps. Although I think I understand what you are asking, I don’t think that converting each card into a structure is what you want to do.