Haskell "Couldn't match expected type ‘a’ with actual type ‘[a0]’"

Haskell "Couldn't match expected type ‘a’ with actual type ‘[a0]’"

我在 Haskell 做一个项目,我试图创建一个函数,它接受两个列表输入,然后 returns 列表的并集,但没有任何重复项。

问题是我不断收到错误消息:

Couldn't match expected type ‘a’ with actual type ‘[t0]’
      ‘a’ is a rigid type variable bound by
          the type signature for newList :: [a] -> [a] -> [a]

这是我的代码:

allList :: (Eq a) => [a] -> [a] -> [a]
allList [] [] = []
allList x y = (x ++ y)

checkDup [] = []
checkDup (z:zs)
    | z `elem` zs = checkDup zs
    | otherwise = z : checkDup zs

newList :: (Eq a) => [a] -> [a] -> [a]
newList [] [] = []
newList x y = [checkDup z | z <- allList x y]

第一个 allList 函数创建两个列表的列表,checkDup 创建一个没有任何重复的新列表,newList 使用列表理解将组合列表传递给checkDup

有人知道我哪里错了吗?

问题出在这里:

newList x y = [checkDup z | z <- allList x y]

z 应该是您传递给 checkDup 的列表,但在这种情况下,z 只是一个元素

也许你想要:

newList x y = checkDup $ allList x y

newList可以声明如下:

newList :: (Eq a) => [a] -> [a] -> [a]
newList = checkDup . allList

既然@Smac89 回答了你的问题,为什么不使用像Data.Set这样的数据表示呢?

import qualified Data.Set as S

allList :: Ord a => [a] -> [a] -> [a]
allList xs ys = S.toList $ S.union (S.fromList xs) (S.fromList ys)

(尽管继续使用 Set 可能更有意义。)

或使用 Data.List:

import Data.List

newList :: Eq a => [a] -> [a] -> [a]
newList xs ys = nub $ xs ++ ys