how does the undecided generic type represents in ghci's runtime

大城市里の小女人 提交于 2019-12-06 01:59:16

As Don Stewart said, type classes in GHC are implemented using "dictionaries". That means that the type class Num is represented as a record of functions (I'm gonna skip the Eq and Show constraints here):

class Num a where
    fromInteger :: Integer -> a
    ...

becomes

data Num a = Num { fromInteger :: Integer -> a, ... }

When you define an instance, a new record is created with the functions from the instance:

instance Num Integer where
    fromInteger = id
    ...

becomes

numDictForInteger = Num { fromInteger = id, ... }

Now, when you use this function in a polymorphic context, the compiler doesn't know which dictionary to use, so it generates an extra parameter for it:

foo :: Num a => a
foo = 1

becomes

foo :: Num a -> a
foo numDict = fromInteger numDict 1

Notice how the constraint Num a => becomes a parameter Num a ->.


However, when you remove the polymorphism, the compiler knows which dictionary to use statically, so it goes ahead and inlines it instead of generating a parameter:

foo :: Integer
foo = 1

becomes

foo :: Integer
foo = fromInteger numDictForInteger 1

As a footnote, this is why the monomorphism restriction exists. A polymorphic value would not be a CAF since it requires the dictionary argument. This might cause significantly different performance characteristics from what you might expect and therefore you're forced to explicitly state that this behavior is what you wanted.

Generic functions that are paramaterized via a type class are represented in GHC as functions that take a "dictionary". This is a data structure containing all the methods of a particular typeclass instance, when instantiated to a given type.

Thus functions may be generic (or "polymorphic") as we say in Haskell, in the typeclass methods.

For more about GHC's representation of values at runtime, see:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!