BufBills
BufBills

Reputation: 8113

What is the good way to print out string with integer in haskell?

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

I do this, but it failed.

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

Upvotes: 0

Views: 1003

Answers (2)

daniel gratzer
daniel gratzer

Reputation: 53901

The first thing to fix is that you're applying printf' to 3 arguments, not 2 like you think. You want to explicitly surround the application of length' in parens.

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

If length' has a sane type (similar to length or genericLength than this will eliminate your type error.

Upvotes: 3

DiegoNolan
DiegoNolan

Reputation: 3766

either putStrLn or putStr. Just use show if the type is of the Show typeclass which most types you will deal with are, or you can write your own instance.

putStr $ show $ length [1..5]

Upvotes: 0

Related Questions