在 Haskell 中获取列表的中间元素时出错

Error while getting the middle element of a list in Haskell

首先,我是 Haskell 的新手,很抱歉提前提出这个问题,因为它看起来有点简单,但我仍然收到此错误消息:

Couldn't match expected type `[a]' with actual type `a'
  `a' is a rigid type variable bound by
      the type signature for middle :: [a] -> a
      at myFile.lhs:18:12
Relevant bindings include
  xs :: [a] (bound at myFile.lhs:20:12)
  x :: a (bound at myFile.lhs:20:10)
  middle :: [a] -> a
    (bound at myFile.lhs:19:2)
In the first argument of `(!!)', namely `x'
In the first argument of `div', namely `x !! length xs'

失败,已加载模块:none。

尝试加载时:

>middle :: [a] -> a
>middle [] = []
>middle (x:xs) = if (l `mod` 2 == 0) then xs !! (l`div` 2) - 1 else x !! l `div` 2
    where l = length xs

如有不明白或不清楚的地方,请评论。

编辑 由于使用 div 我得到:

Error:     No instance for (Integral a) arising from a use of `div'
Possible fix:
  add (Integral a) to the context of
    the type signature for middle :: [a] -> a
In the expression: xs !! l `div` 2
In the expression:
  if (l `mod` 2 == 0) then xs !! (l `div` 2) - 1 else xs !! l `div` 2
In an equation for `middle':
    middle (x : xs)
      = if (l `mod` 2 == 0) then
            xs !! (l `div` 2) - 1
        else
            xs !! l `div` 2
      where
          l = length xs

注意x只是一个元素,不是列表。所以,使用 x !! anything 是一个类型错误。您是指 xs !! anything 吗?

此外,

middle [] = []

是错误的,因为您必须 return 一个元素,而不是一个列表。由于没有中间元素,我们只能return底部,例如

middle [] = error "middle: empty list"

以上使该函数成为部分函数,​​即如果在较大的程序中您使用空列表调用该函数,程序将崩溃。

如果你想禁止,你可以将类型更改为Maybe:

middle :: [a] -> Maybe a
middle []     = Nothing
middle (x:xs) = Just (.....)