如何使用实例?

时间:2011-04-16 10:53:05

标签: haskell

错误讯息:

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.

源代码:

    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);}

2 个答案:

答案 0 :(得分:4)

节目约为:: a - &gt;串

它将值转换为String,但不会将其打印到屏幕上。

执行需要IO操作才能将字符串实际打印到屏幕,通常是

putStr :: String -> IO ()

所以试试:

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

更简洁打印结合了两者:

main = do { print (ppLetter 3) }

答案 1 :(得分:2)

有关更新的问题,请替换

main = do {print (ppLetter 3);}

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