Haskell 每个数字的列表不等于假工作,但在相同的数字上不工作

Haskell 每个数字的列表不等于假工作,但在相同的数字上不工作,haskell,Haskell,下面我展示了输出。我给出了一个数字列表,如果它们不相等,则返回False,其工作正常。但是如果列表中的数字相等,那么它就不会返回True。你能查一下这个密码吗 la [] = True la a = if ((head a )==head (tail a)) then la (tail a) else False 输出: Cw2016> la [1,2,2] False Cw2016> la [2,2,2] Program er

下面我展示了输出。我给出了一个数字列表,如果它们不相等,则返回False,其工作正常。但是如果列表中的数字相等,那么它就不会返回True。你能查一下这个密码吗

la [] = True
la a =
      if ((head a )==head (tail a))
          then la (tail a)
          else False
输出:

Cw2016> la [1,2,2]
False
Cw2016> la [2,2,2]

Program error: pattern match failure: head []

Cw2016> la [2,2,3]
False
Cw2016> la [0,1,3]
False
Cw2016> la [0,0,3]
False
Cw2016> la [0,0,0]

Program error: pattern match failure: head []

Cw2016> 

问题是在第二个分支中,您只知道列表的大小至少为1,但您正在寻找第二个参数。我建议您使用模式匹配替换头部和尾部(这是部分功能):

la [] = True
la (x0:x1:xs) =
      if (x0 == x1)
          then la (x1:xs)
          else False
如果您使用-W调用ghc,您将得到警告,您的模式没有覆盖x:[]。您可能要添加此分支:

la (x0:[]) = True
顺便说一下,您应该简化您的表达式:

      if (x0 == x1)
          then la (x1:xs)
          else False
致:

为了让您的问题更具技术性,对于某些
x
,当
a=[x]
时会出现问题。首先,
head
tail
被定义为:

head (x:xs) = x
head [] = undefined

tail (x:xs) = xs
tail [] = undefined
然后,表达式
head(tail a)
的计算结果如下:

  head (tail a)
=  { value of a }
  head (tail (x:[]))
=  { first equation of tail }
  head []
=  { second equation of head }
  undefined

这就是为什么会出现错误。

逐步执行
la[1]
的求值
la(x:xs)
更容易阅读,因为
head(x:xs)=x
tail(x:xs)=xs
  head (tail a)
=  { value of a }
  head (tail (x:[]))
=  { first equation of tail }
  head []
=  { second equation of head }
  undefined