这是原始问题:
修改问题10的结果,使得如果元素没有重复,则只需将其复制到结果列表中。只有带有重复项的元素才会作为(N E)列表传输。
示例:
* (encode-modified '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))
Haskell中的示例:
ghci> encodeModified "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']
这是我的解决方案:
import Data.List
data Encode a = Single a | Multiple Int a deriving (Show)
encodeModified :: (Eq a) => [a] -> [Encode a]
encodeModified xs = [y | x <- group xs, let y = if (length x) == 1 then Single (head x) else Multiple (length x) (head x)]
encodeModified' = map (\xs -> if (length xs == 1) then Single (head xs) else Multiple (length xs) (head xs)) . group
我的GHCI是7.10.3,当我执行:l xx.hs时,它给了我:
No instance for (Eq a0) arising from a use of ‘group’
The type variable ‘a0’ is ambiguous
Relevant bindings include
encodeModified' :: [a0] -> [Encode a0] (bound at 11.hs:8:1)
Note: there are several potential instances:
instance (Eq a, Eq b) => Eq (Either a b)
-- Defined in ‘Data.Either’
instance forall (k :: BOX) (s :: k). Eq (Data.Proxy.Proxy s)
-- Defined in ‘Data.Proxy’
instance (GHC.Arr.Ix i, Eq e) => Eq (GHC.Arr.Array i e)
-- Defined in ‘GHC.Arr’
...plus 27 others
In the second argument of ‘(.)’, namely ‘group’
In the expression:
map
(\ xs
-> if (length xs == 1) then
Single (head xs)
else
Multiple (length xs) (head xs))
. group
In an equation for ‘encodeModified'’:
encodeModified'
= map
(\ xs
-> if (length xs == 1) then
Single (head xs)
else
Multiple (length xs) (head xs))
. group
我无法通过反馈找出错误是什么,如果有人可以帮助我,我的方法没有发现任何问题?感谢。
答案 0 :(得分:3)
此处的代码包含Eq a
类型的encodeModified
约束,但是根据您发布的错误,我可以看到您文件中实际存在encodeModified'
的类型(注意素数!)没有那个约束。添加约束,你应该很高兴。
将来,发布实际有问题的代码是礼貌的。