error Couldn't match expected type ‘Char’ with actual type ‘[Char]’

I am trying to build a string representation for the show function of a typeclass representing a polynomial. I keep getting type errors of a mismatch from 'Char' to '[Char]', but from my understanding haskell's "append" function should be able to concatenate a Char to a string/[Char]. I don't understand where the problem lies, or where to look for a solution based on the errors I receive. here is the faulty code:

newtype Poly a = P [a]

instance (Num a, Show a) => Show (Poly a) where
    show p = ["" : form (p !! i) i | i <- [l,(l-1)..0]]
        where
            l = length p
            form e i 
                | i == 0 = elem
                | i == 1 = elem ++ "x + "
                | otherwise = elem ++ "x^" ++ (show i) ++ " + "
                    where elem = show e

any help would be greatly appreciated, thanks in advance.


You write

from my understanding haskell's "append" function should be able to concatenate a Char to a string/[Char].

I have no idea where you got this idea. It's wrong. I'm guessing you've defined

type Poly a = [a]

and I'll go with that assumption.

instance (Num a, Show a) => Show (Poly a) where

This is wrong. Poly is a type synonym. You can only declare instances for proper first-class types (the application of a type constructor to zero or more type variables). You can fix this by using, instead,

newtype Poly a = Poly {getPoly :: [a]}

but then you need to wrap/unwrap the Poly data constructor as required. Once you've gotten this right, you'll probably see that the Num constraint you've given is unnecessary.

show p = ["" ++ form (p !! i) i | i <- [(length p)..0]]

There are a few problems. The big one is that this does not define a string (list of characters) but rather a list of strings. You can fix this, generally, by applying concat to the result. The second one is that "" ++ anything is just anything , because concatenating the empty list to another list doesn't do anything. The third problem is that you're trying to count down, but you've done it wrong. That notation only counts up. To count down, you have to show that you want to count down:

let lp = length p in [lp, (lp-1) .. 0]

The last thing I see immediately (some of these mistakes are repeated in the preceding two lines):

    | otherwise = e ++ "x^" ++ i ++ " + "

Now i is an Int , and ++ only works for lists. So that will not work. You need to first convert i to a string using show . e is of type a , and needs to be converted to a string using show as well.

链接地址: http://www.djcxy.com/p/43526.html

上一篇: 声明一个类型类的列表实例

下一篇: 错误无法匹配预期类型'Char'与实际类型'[Char]'