在haskell中打印带整数字符串的好方法是什么?

时间:2013-09-23 03:06:08

标签: haskell

import Text.Printf
printf "the length of this list is %d"  length' [1,2,3,4,5]

我这样做,但失败了。

'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, ....]"

2 个答案:

答案 0 :(得分:3)

要解决的第一件事是你将printf'应用于3个参数,而不是你认为的2个参数。您希望明确地将length'的应用程序包含在parens中。

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

如果length'具有理智的类型(类似于lengthgenericLength,则会消除您的类型错误。

答案 1 :(得分:0)

putStrLnputStr。如果类型属于您将要处理的大多数类型的show类型类,只需使用Show,或者您可以编写自己的实例。

putStr $ show $ length [1..5]
相关问题