所以,我有这个结构:
defmodule Card do
defstruct id: nil, result_numbers: [], owned_numbers: []
end
对于每个实例,我都会计算
owned_numbers
和 result_numbers
中的 CardEvaluator.evaluate_card()
的总数(该位经过测试并且有效)。
然后,我从
(card.id + 1)..(card.id + value)
构建一系列值,其中值是卡片评估器返回的值。
然后我想使用该范围内每个索引中的卡递归调用我的
process_card_reward
方法。因此,如果卡 2 的值为 3,我会用第三张、第四张和第五张卡来调用 process_card_reward
。然后我想总结制作的卡片总数。
我有这个:
def process_scratchcards(card_strings) do
cards =
card_strings
|> Enum.map(&CardParser.parse_card/1)
|> IO.inspect()
total_reward = cards
|> Enum.map(fn card -> process_card_reward(card, cards) end)
|> Enum.sum()
IO.puts(total_reward)
total_reward
end
def process_card_reward(card, all_cards) do
value =
card
|> CardEvaluator.evaluate_card()
victory_range = (card.id + 1)..(card.id + value)
IO.inspect(victory_range)
num_children =
Enum.reduce(victory_range, 0, fn n, acc ->
acc + process_card_reward(Enum.at(all_cards,n), all_cards)
end)
IO.puts(num_children)
num_children + 1
end
但是我遇到了这个我不明白的异常:
test 正确处理测试数据(ScratchcardsTest) 测试/scratchcards_test.exs:5 ** (KeyError) key:owned_numbers not found in: nil
如果您使用点语法,例如map.field,请确保点的左侧是地图 代码: |> Scratchcards.process_scratchcards() 堆栈跟踪: (刮刮卡 0.1.0)lib/card_evaluator.ex:3: CardEvaluator.evaluate_card/1 (scratchcards 0.1.0) lib/scratchcards.ex:19: Scratchcards.process_card_reward/2 (scratchcards 0.1.0) lib/scratchcards.ex:26: Scratchcards.process_card_reward/2 中的匿名 fn/3 (elixir 1.15.7) lib/enum.ex:4379: Enum.reduce/3 (scratchcards 0.1.0) lib/scratchcards.ex:25: Scratchcards.process_card_reward/2 (scratchcards 0.1.0) lib/scratchcards.ex:26: Scratchcards.process_card_reward/2 中的匿名 fn/3 (elixir 1.15.7) lib/enum.ex:4379: Enum.reduce/3 (scratchcards 0.1.0) lib/scratchcards.ex:25: Scratchcards.process_card_reward/2 (scratchcards 0.1.0) lib/scratchcards.ex:26: Scratchcards.process_card_reward/2 中的匿名 fn/3 (elixir 1.15.7) lib/enum.ex:4379: Enum.reduce/3 (scratchcards 0.1.0) lib/scratchcards.ex:25: Scratchcards.process_card_reward/2 (elixir 1.15.7) lib/enum.ex:1693: Enum."-map/2-lists^map/1-1-"/2 (scratchcards 0.1.0) lib/scratchcards.ex:9: Scratchcards.process_scratchcards/1 测试/scratchcards_test.exs:18:(测试)
我该如何解决这个问题?
但是我遇到了这个我不明白的异常:
test 正确处理测试数据(ScratchcardsTest) test/scratchcards_test.exs:5 ** (KeyError) key :owned_numbers 不是 发现于:无
iex(1)> map = %{a: 1, b: 2, owned_numbers: 3}
%{a: 1, b: 2, owned_numbers: 3}
iex(2)> map.owned_numbers
3
iex(3)> map = nil
nil
iex(4)> map.owned_numbers
** (KeyError) key :owned_numbers not found in: nil. If
you are using the dot syntax, such as map.field,
make sure the left-hand side of the dot is a map