What is the difference between these two function type definitions?

For the following trivial function definitions:

printLength1::(Num a)=>String->a
printLength1 s = length s


printLength2::String->Int
printLength2 s = length s

Why aren't they the same? In what situations should I choose one over the other?

And I get this error for printLength1:

Couldn't match type `a' with `Int'
      `a' is a rigid type variable bound by
          the type signature for rpnc :: String -> a at test.hs:20:1
    In the return type of a call of `length'
    In the expression: length s
    In an equation for `rpnc': rpnc s = length s

I understand this error. But how can I fix this? I already read some posts here about a variable of hard type, but still could not figure out how to fix it.

+5
source share
2 answers

The signature of the first type is more general. This means that the result can be any Num- it is polymorphic in return type. Thus, the result of your first function can be used as Int, or Integeror any other instance Num.

, length Int, - Num. , fromIntegral:

printLength1 :: Num a => String -> a
printLength1 s = fromIntegral $ length s

, fromIntegral . length ( ) Num c => [a] -> c. , printLength1.

+9

LearnYouAHaskell.com:

. numLongChains:: Int, Int Num a . Num a, fromIntegral .

+7

All Articles