1
嘗試一個elixir教程,我發現這個遞歸非常有趣的構造。Elixir模式匹配頭列表
所以我有一個列表:
flares = [
%{classification: :X, scale: 99, date: Date.from({1859, 8, 29})},
%{classification: :M, scale: 5.8, date: Date.from({2015, 1, 12})},
%{classification: :M, scale: 1.2, date: Date.from({2015, 2, 9})},
%{classification: :C, scale: 3.2, date: Date.from({2015, 4, 18})},
%{classification: :M, scale: 83.6, date: Date.from({2015, 6, 23})},
%{classification: :C, scale: 2.5, date: Date.from({2015, 7, 4})},
%{classification: :X, scale: 72, date: Date.from({2012, 7, 23})},
%{classification: :X, scale: 45, date: Date.from({2003, 11, 4})}
]
我想計算的scale
的但每個分類的公差的總和。我希望我可以做這樣的事情:
def total_flare_power(flares), do: total_flare_power(flares, 0)
def total_flare_power([%head{classification: :M} | tail], total) do
total_flare_power(tail, total + head.scale * 0.92)
end
def total_flare_power([%head{classification: :C} | tail], total) do
total_flare_power(tail, total + head.scale * 0.78)
end
def total_flare_power([%head{classification: :X} | tail], total) do
total_flare_power(tail, total + head.scale * 0.68)
end
def total_flare_power([], total), do: total
但我endup與此錯誤消息:
** (FunctionClauseError) no function clause matching in Solar.total_flare_power/2
看起來像我的命名結構,我試圖在不工作的頭相匹配。
謝謝了,我知道地圖,但是因爲我正在學習語言,所以我想自己實現這個東西。 – Calin