开发者

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 to Int. While there are often generic* functions such as genericLength, these names are longer and not in the Prelude.

  • Performance of Int is more easily understood. Performance for Integral a depends on a large part on if the function gets specialized for the particular instance of Integral.

  • Int is often not just sufficient but also honest. For example, strict ByteStrings can't be over an Int size (typically, please don't comment with esoteric examples) assuming your compiler uses machine word or larger Ints 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜