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

2 回答 2

3

首先要解决的是您正在应用printf'3 个参数,而不是您认为的 2 个参数。您想明确地包围length'in parens 的应用。

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

如果length'有一个健全的类型(类似于lengthgenericLength比这将消除你的类型错误。

于 2013-09-23T03:33:02.040 回答
0

要么putStrLn要么putStr。如果show类型是Show您将要处理的大多数类型的类型类,请使用,或者您可以编写自己的实例。

putStr $ show $ length [1..5]
于 2013-09-23T03:25:36.023 回答