Why do 3 and x (which was assigned 3) have different inferred types in Haskell? -
this question has answer here:
- what monomorphism restriction? 1 answer
type inference in haskell has bit of learning curve (to least!). way start learning simple examples. so, following bit of "hello world" type inference.
consider following example:
prelude> :t 3 3 :: (num t) => t prelude> let x = 3 prelude> :t x x :: integer
the question thus: why 3 , x have different types?
link summary:
read answers below full story; here's link summary:
- ghc type defaulting: haskell report section 4.3.4
- ghci's extended type defaulting: using ghci section 2.4.5
- monomorphic restriction: haskell wiki
there's factor here, mentioned in of links acfoltzer includes, might worth making explicit here. you're encountering effect of monomorphism restriction. when say
let x = 5
you make top-level definition of variable. mr insists such definitions, when otherwise unaccompanied type signature, should specialized monomorphic value choosing (hopefully) suitable default instances unresolved type variables. contrast, when use :t
ask inferred type, no such restriction or defaulting imposed. so
> :t 3 3 :: (num t) => t
because 3
indeed overloaded: admitted numeric type. defaulting rules choose integer
default numeric type, so
> let x = 3 > :t x x :: integer
but let's switch off mr.
> :set -xnomonomorphismrestriction > let y = 3 > :t y y :: (num t) => t
without mr, definition polymorphic can be, overloaded 3
. checking...
> :t y * (2.5 :: float) y * (2.5 :: float) :: float > :t y * (3 :: int) y * (3 :: int) :: int
note polymorphic y = 3
being differently specialized in these uses, according frominteger
method supplied relevant num
instance. is, y
not associated particular representation of 3
, rather scheme constructing representations of 3
. naïvely compiled, that's recipe slow, people cite motivation mr.
i'm (locally pretending be) neutral on debate whether monomorphism restriction lesser or greater evil. write type signatures top-level definitions, there no ambiguity i'm trying achieve , mr beside point.
when trying learn how type system works, it's useful separate aspects of type inference which
‘follow plan’, specializing polymorphic definitions particular use cases: robust matter of constraint-solving, requiring basic unification , instance resolution backchaining; and
‘guess plan’, generalizing types assign polymorphic type scheme definition no type signature: that's quite fragile, , more move past basic hindley-milner discipline, type classes, higher-rank polymorphism, gadts, stranger things become.
it's learn how first works, , understand why second difficult. of weirdness in type inference associated second, , heuristics monomorphism restriction trying deliver useful default behaviour in face of ambiguity.
Comments
Post a Comment