Jo0o0
Jo0o0

Reputation: 531

How to use instance?

Error message:

ho8.hs:17:19:
    Ambiguous type variable `a0' in the constraints:
      (PPLetter a0) arising from a use of `ppLetter' at ho8.hs:17:19-26
      (Num a0) arising from the literal `3' at ho8.hs:17:28
    Probable fix: add a type signature that fixes these type variable(s)
    In the first argument of `print', namely `(ppLetter 3)'
    In the expression: print (ppLetter 3)
    In the expression: do { print (ppLetter 3) }
Failed, modules loaded: none.

Source code:

    module Main where
import Data.List(nub)

import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,int,(<>),(<+>),($+$),render)

class PPLetter a where
 ppLetter :: a -> Doc

instance PPLetter Int where
 ppLetter a = text ("p"++show a)

instance PPLetter Char where
 ppLetter = PP.char


main = do {print (ppLetter 3);}

Upvotes: 0

Views: 201

Answers (2)

dave4420
dave4420

Reputation: 47042

For your updated question, replace

main = do {print (ppLetter 3);}

with

main = do {print (ppLetter (3 :: Int));}

Upvotes: 2

stephen tetley
stephen tetley

Reputation: 4493

show is approximately :: a -> String

It turns a value into a String, but does not print it to screen.

do needs a IO action to actually print a String to screen, typically

putStr :: String -> IO ()

so try:

main = do { putStr (show (ppLetter 3)) }

More succinctly print combines the two:

main = do { print (ppLetter 3) }

Upvotes: 4

Related Questions