Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As Don Stewart said, type classes in GHC are implemented using "dictionaries". That means that the type class <code>Num</code> is represented as a record of functions (I'm gonna skip the <code>Eq</code> and <code>Show</code> constraints here):</p> <pre><code>class Num a where fromInteger :: Integer -&gt; a ... </code></pre> <p>becomes</p> <pre><code>data Num a = Num { fromInteger :: Integer -&gt; a, ... } </code></pre> <hr> <p>When you define an instance, a new record is created with the functions from the instance:</p> <pre><code>instance Num Integer where fromInteger = id ... </code></pre> <p>becomes</p> <pre><code>numDictForInteger = Num { fromInteger = id, ... } </code></pre> <hr> <p>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:</p> <pre><code>foo :: Num a =&gt; a foo = 1 </code></pre> <p>becomes</p> <pre><code>foo :: Num a -&gt; a foo numDict = fromInteger numDict 1 </code></pre> <p>Notice how the constraint <code>Num a =&gt;</code> becomes a parameter <code>Num a -&gt;</code>.</p> <hr> <p>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:</p> <pre><code>foo :: Integer foo = 1 </code></pre> <p>becomes</p> <pre><code>foo :: Integer foo = fromInteger numDictForInteger 1 </code></pre> <hr> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload