This is the original question:
Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
Example:
* (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))
Example in Haskell:
ghci> encodeModified "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']
This is my solution:
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
My GHCI is 7.10.3, when I execute :l xx.hs, it gives me:
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
I can't figure out what's the error by its feedback and I didn't find anything wrong with my method, if someone can help me? thanks.