Using Int type vs. Integral constraint. Advantage?
Consider these (more or less) equivalent type signatures:
f1 :: [a] -> Int -> a
f2 :: Integral b => [a] -> b -> a
f2 is more general than f1, and that is a big advantage, but is there an advantage of f1 over f2?
It seems that in the solutions to the H-开发者_Go百科99 problems, and in many posted solutions to various Project Euler problems, the f1 form appears much more often than the f2.
I'm not sure why. Is it simply programmer laziness, or is there a performance cost in going with the more general version (f2), or is there another reason?
Often this is due to people wanting to use the integral in conjunction with results from
length
and other functions already constrained toInt
. While there are oftengeneric
* functions such asgenericLength
, these names are longer and not in the Prelude.Performance of
Int
is more easily understood. Performance forIntegral a
depends on a large part on if the function gets specialized for the particular instance ofIntegral
.Int
is often not just sufficient but also honest. For example, strictByteString
s can't be over anInt
size (typically, please don't comment with esoteric examples) assuming your compiler uses machine word or largerInt
s and not the darned standard 29+ bits.Overuse of type classes muddies up the signatures, making the language less readable. Were extreme generalization to become common, particularly for the primitive functions, I think we would need to find a more succinct way to express the constraints to keep from driving programmers mad.
精彩评论