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

时间:2015-05-17 09:19:51

标签: list function haskell elements

首先,我对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'

失败,模块加载:无。

尝试加载时:

>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

1 个答案:

答案 0 :(得分:1)

请注意,x只是一个元素,而不是列表。因此,使用x !! anything是一种类型错误。你的意思是xs !! anything吗?

此外,

middle [] = []

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

middle [] = error "middle: empty list"

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

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

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