【问题标题】:Elixir pattern matching head in a list列表中的 Elixir 模式匹配头
【发布时间】:2016-11-07 11:20:29
【问题描述】:

尝试了一个长生不老药教程,我发现了这个非常有趣的递归构造。

所以我有一个清单:

    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

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

【问题讨论】:

    标签: elixir


    【解决方案1】:

    你在做

    %head{classification: :M}
    

    匹配head 类型的structs:Mclassification。你的意思可能是:

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

    匹配:classification下的任何带有:m的映射并将其绑定到变量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,无需分配模式匹配的结果。

    【讨论】:

    • 非常感谢,我知道地图,但由于我正在学习语言,所以我想自己实现这些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2018-11-24
    • 2017-03-06
    相关资源
    最近更新 更多