Elixir模式匹配头列表中

时间:2016-07-05 14:50:21

标签: 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

但我最终会收到此错误消息:

 ** (FunctionClauseError) no function clause matching in Solar.total_flare_power/2

看起来我正在尝试匹配头部的命名结构不起作用。

1 个答案:

答案 0 :(得分:2)

你正在做

%head{classification: :M}

匹配structs headclassification :M的{​​{1}}。你的意思是:

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,而无需指定模式匹配的结果。