If you write something like:
length' :: (Integral a) => a -> a
it means that the function will work for any a
where Integral a
holds. So that means that a programmer that uses length'
could decide to use it as: length' :: Integer -> Integer
. Since length
however does not return an Integer
(but an Int
), Haskell can not provide such function length'
.
Your function has another problem as well: you call show
on a
. This means that a
has to be an instance of the Show
class. So you should add a type constraint Show a
. There is no need to restrict to Integral a
, since you can use the function for everything that is Show
. So the type signature should be:
length' :: Show a => a -> Int
length' = length . show
If you want to give the user the freedom to use any Num n
as output type, you can use the genericLength :: Num n => [a] -> n
function:
import Data.List(genericLength)
length' :: (Show a, Num n) => a -> n
length' = genericLength . show
Int
and here you make a claim that the type can be anyIntegral
type. – Willem Van OnsemfromIntegral :: (Integral a, Num b) => a -> b
to convert from anInt
to anyNum
(and allIntegral
s areNum
s so that works). – gallais