Thank you for working that through.
- In the
sample
function, what is stopping the Enum.reduce/3
function from always returning 0 when the accumulator’s starting value for :a and :b are 0?
- In the 3rd argument of
Enum.reduce/3
, you are passing &do_sample/2
. What are the arguments that are passed to &do_sample/2
? Are the arguments line_items
and %{a: 0, b: 0}
?
- Do you have any learning resources/tutorials that explain exercises containing pattern matching in function heads and advanced uses of function capture operators?
- I added attribute property and am trying to pattern match against like attribute values. Does this look correct?
New data structure
%SomeStruct{
price_a: 2,
price_b: 3,
line_items: [
%LineItems{
height: 5,
width: 8,
type: "a",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 3,
width: 2,
type: "b",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 4,
width: 6,
type: "a",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 5,
width: 7,
type: "b",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 4,
width: 7,
type: "a",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 2,
width: 6,
type: "b",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 8,
width: 4,
type: "a",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
},
%LineItems{
height: 3,
width: 3,
type: "b",
attribute_1: "w",
attribute_2: "x",
attribute_3: "w",
attribute_4: "x"
}
]
}
New code
def sample(%{line_items: line_items, price_a: price_a, price_b: price_b}) do
line_items
|> Enum.reduce(%{type_a: 0, type_b: 0}, &do_sample/2)
|> Map.update!(:type_a, &(&1 * price_a))
|> Map.update!(:type_b, &(&1 * price_b))
end
defp do_sample(%{width: width, attribute_1: "w"}, acc), do: Map.update!(acc, :type_a, & &1 + width)
defp do_sample(%{height: height, attribute_2: "w"}, acc), do: Map.update!(acc, :type_a, & &1 + height)
defp do_sample(%{width: width, attribute_3: "w"}, acc), do: Map.update!(acc, :type_a, & &1 + width)
defp do_sample(%{height: height, attribute_4: "w"}, acc), do: Map.update!(acc, :type_a, & &1 + height)
defp do_sample(%{width: width, attribute_1: "x"}, acc), do: Map.update!(acc, :type_b, & &1 + width)
defp do_sample(%{height: height, attribute_2: "x"}, acc), do: Map.update!(acc, :type_b, & &1 + height)
defp do_sample(%{width: width, attribute_3: "x"}, acc), do: Map.update!(acc, :type_b, & &1 + width)
defp do_sample(%{height: height, attribute_4: "x"}, acc), do: Map.update!(acc, :type_b, & &1 + height)