2013-09-23 30 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

相关问题