[%{"item" => "i0...">

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.

+4
source share
2 answers

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.

0
source

@zaboco , struct/2 , .

Enum.map:

Enum.map(recos["itemScores"], fn %{"item" => item, "score" => score} -> %RecommendedItem{item: item, score: score} end)

.

+1

Source: https://habr.com/ru/post/1629443/


All Articles