2016-07-05 64 views
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 

看起來像我的命名結構,我試圖在不工作的頭相匹配。

回答

2

你做

%head{classification: :M} 

匹配與:Mclassification類型headstructs。你大概的意思是:

def total_flare_power([%{classification: :M} = head | tail], total) do 
... 
end 

:m任何地圖:classification下匹配,並將其綁定到變量head。順便說一句,你可能要提取您的邏輯計算調整後的規模和總結那些庫函數是這樣的:

flares 
|> Enum.map(fn 
    %{classification: :M, scale: scale} -> scale * 0.92 
    %{classification: :C, scale: scale} -> scale * 0.78 
    %{classification: :X, scale: scale} -> scale * 0.68 
end) 
|> Enum.sum 

此版本還訪問scale通過解構,而無需指定模式匹配的結果。

+0

謝謝了,我知道地圖,但是因爲我正在學習語言,所以我想自己實現這個東西。 – Calin