【问题标题】:How to pattern match head in a list in function?如何在功能列表中模式匹配头部?
【发布时间】:2022-12-01 15:50:53
【问题描述】:

我有一个整数和原子混合的列表。我想将列表的头部与原子匹配,否则为整数。

lst = [1,2,3,4,5,6, :eoe, 7,8,9,10,11,12. :eoe]

我最初尝试过这种方式:


defmodule Test do
  def test(lst) do
    helper(lst, 0, 0, 1)
  end

  def helper([], _p, total, e) do
    IO.puts "#{e} #{t}"
  end

  def helper([:eoe , t], _p, total, e) do   # <--- This function never called even though head is at some point :eoe
    IO.puts "#{e} #{total}"

    helper(t, "", 0, elf + 1)
  end

  def helper([h | t], p, total, e) do
    h
    |> is_atom()
    |> IO.inspect()

    helper(t, h, total + h, e)

  end
end

然后添加守卫以明确缩小模式匹配范围

...

def helper([:eoe = head , t], _p, total, e) when is_atom(head) do
...

def helper([h | t], p, total, e) when is_integer(h) do
...

def helper([:eoe = h , t], _p, total, e) when is_atom(h) do这个函数没有被调用。它总是匹配def helper([h | t], p, total, e) when is_integer(h) do这个。我什至把前一个放在后一个之前。我希望它与:eoe匹配

【问题讨论】:

  • 尝试使用 [:eoe = h | t] 而不是 [:eoe = h, t] ;)
  • 我不敢相信这是一个语法错误。我快疯了。 @BrujoBenavides

标签: list functional-programming erlang elixir pattern-matching


【解决方案1】:

要匹配头部,应使用 [h | t] 表示法。 [h, t] 将匹配列表元素。

- def helper([:eoe = h, t]
+ def helper([:eoe = h | t]

此外,when is_atom(h) guard 是多余的,一旦你直接在原子上进行模式匹配。也就是说,以下任何一项都可以。

def helper([:eoe | t], _p, total, e) do
def helper([h | t], _p, total, e) when h == :eoe do
def helper([h | t], _p, total, e) when h in [:eoe] do
def helper([h | t], _p, total, e) when is_atom(h) do # match any atom

【讨论】:

  • 我添加了守卫以明确缩小模式匹配的范围,因为我认为有些事情很奇怪,结果证明这是一个语法错误。
  • 未来的访问者可能会遇到同样的问题,因此本网站上的答案与原始问题存在争议 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 2015-03-16
  • 1970-01-01
  • 2016-11-08
相关资源
最近更新 更多