Curious case of type of 2 in haskell -
what rationale behind assigning general type num => a
2
instead of defaulting specific type int
or integer
?
secondly have read @ many places 2
polymorphic value definition of polymorphism doesn't admit constrained variables. 2
polymorphic in haskell?
2
polymorphic can use whatever type of number like. num
type class has function frominteger
, used here. 2
frominteger (2 :: integer)
. if 2
not polymorphic have write if wanted non-integer number, because there no automatic coercion in haskell (i.e. can't (1 :: integer) + (1 :: int)
). case fractional
fromrational
way.
polymorphic type variables can have constraints. if not have constraints, called parametric polymorphism , if constrained, bounded parametric or ad-hoc polymorphism. see haskellwiki article on polymorphism.
be aware, should not rely on type inference top-level functions or else may fall trap monomorphism restriction. example if write @ top-level of module:
polymorphic = 42
you may expect polymorphic
of type num => a
, in reality haskell default type of polymorphic
integer
.
Comments
Post a Comment