输入‘xs’解析错误的问题[Haskell]

Problems of parse error on input ‘xs’ [ Haskell ]

newtype Set a = Set { unSet :: [a] }
    deriving (Read, Show, Eq, Ord)

reduca :: (Eq a, Ord a) => [a] -> Set a
reduca [] = Set { }
reduca (x:xs) | x `myelem` xs   = Set { reduca xs }
                | otherwise       = Set { x : reduca xs }
    where myelem :: (Eq a, Ord a) => a -> [a] -> Bool
          myelem x [] = False
          myelem x (y:ys)
            | x == y = True
            | otherwise = myelem x (ys)

我在编译这段 Haskell 代码时遇到了问题。开始时创建一个集合,'reduca' 的功能旨在删除列表中重复的元素。 错误显示

Prelude> :l reduca
[1 of 1] Compiling Main             ( reduca.hs, interpreted )

reduca.hs:26:52: error: parse error on input ‘xs’
   |
26 | reduca (x:xs) | x `myelem` xs   = Set { reduca xs }
   |                                                ^^
Failed, no modules loaded.

我该如何更改它?非常感谢您的帮助!

您可以通过两种方式在这里构建 Sets:作为 Set (reduca xs)Set { unSet = reduca xs },但不能将两者组合。

因此您可以构造 Set 与:

reduca :: (Eq a, Ord a) => [a] -> Set a
reduca [] = Set ( [] )
reduca (x:xs) | x `myelem` xs   = Set (reduca xs)
              | otherwise       = Set (x : reduca xs)
    where …

这将不起作用,因为 reduca xs returns a Set a,而当使用 Set (reduca xs) 表达式时,这需要是一个列表 ([a]) .

您可以使用将结果包装在一个集合中的辅助函数来实现它,因此:

reduca :: (Eq a, Ord a) => [a] -> Set a
reduca ls = Set ( uniq ls )
  where uniq [] = []
        uniq (x:xs)
          | x `elem` xs = uniq xs
          | otherwise = x : uniq xs