2013-09-23 39 views
0
import Text.Printf 
printf "the length of this list is %d" length' [1,2,3,4,5] 

我這樣做,但是失敗了。在haskell中用整數打印出字符串的好方法是什麼?

'func.hs:38:58: 
    No instance for (Num t0) arising from the literal `1' 
    The type variable `t0' is ambiguous 
    Possible fix: add a type signature that fixes these type variable(s) 
    Note: there are several potential instances: 
     instance Num Double -- Defined in `GHC.Float' 
     instance Num Float -- Defined in `GHC.Float' 
     instance Integral a => Num (GHC.Real.Ratio a) 
     -- Defined in `GHC.Real' 
     ...plus three others 
    In the expression: 1 
    In the third argument of `printf', namely `[1, 2, 3, 4, ....]' 
    In a stmt of a 'do' block: 
     printf "the length of this list is %d" length' [1, 2, 3, 4, ....]" 
+0

什麼長「? – jozefg

+2

我猜你的意思是封裝''長」 [1, 2,3,4,5]''在括號中。 – fjarri

回答

3

解決的第一件事情是,你申請printf'到3個參數,不喜歡你的想法。你想明確地圍繞在parens中的應用。

printf "string" (length' [1, 2, 3, 4]) 
printf "string" $ length' [1, 2, 3, 4] -- The more idiomatic version of the above. 

如果length'有理智型(類似lengthgenericLength比這將消除你的錯誤類型。

0

要麼putStrLnputStr。只需使用show如果類型是Show類型類大多數類型的你會處理的,或者你可以寫自己的實例。

putStr $ show $ length [1..5] 
+0

'putStr。show'是一回事'print'。 – kqr

+0

@kqr它實際上'putStrLn。show' – jozefg

+0

@jozefg糟糕,評論是我的咖啡前!我的觀點仍然有效,但 - 如果你要使用'putStrLn'可以一樣好使用'print'。 – kqr

相關問題