title: How can GHC convert a polymorphic numeric literal into an arbitrary type with an instance of Num?
body: <p>As far as I can tell, GHC can convert any numeric literal with default polymorphic type <code>Num a =&gt; a</code> into any type with an instance of <code>Num</code>. I'd like to know whether this is true and a little about the underlying mechanism.</p>
  
  <p>To explore this, I have written a datatype called <code>MySum</code> which replicates (part of) the functionality of <code>Sum</code> from Data.Monoid. The most important part is that it contains <code>instance Num a =&gt; Num (MySum a)</code>.</p>
  
  <p>Note - This just so happens to be where my question go its start. The Monoid is not specifically relevant. I've included a portion of that code at the bottom of this question, just in case it is useful for an answer to refer to the contents. </p>
  
  <p>It seems that GHCi will happily comply with an input of the form "v :: MySum t", under the following conditions:</p>
  
  <ol>
  <li><p>v is a polymorphic value of type <code>Num a =&gt; a</code></p></li>
  <li><p>t is a (possibly polymorphic) type under <code>Num</code></p></li>
  </ol>
  
  <p>As far as I can tell, the only numeric literals compatible with the type <code>Num a =&gt; a</code> are ones that look like integers. Is this always the case? It seems to imply that a value can instantiated to any type under Num exactly when that value is integral. If this is correct, then I understand how something like <code>5 :: MySum Int</code> might work, given the function <code>fromInteger</code> in <code>Num</code>.</p>
  
  <p>With all of that said, I can't figure out how something like this works:</p>
  
  <pre><code>*Main Data.Monoid&gt; 5 :: Fractional a =&gt; MySum a
  MySum {getMySum = 5.0}
  </code></pre>
  
  <p>If it's possible to explain this in a novice-friendly way, I would appreciate it.</p>
  
  <hr>
  
  <p>The instance <code>Num a =&gt; Num (MySum a)</code>, as promised:</p>
  
  <pre><code>import Control.Applicative
  
  newtype MySum a = MySum {getMySum :: a}
    deriving Show
  
  instance Functor MySum where
    fmap f (MySum a) = MySum (f a)
  
  instance Applicative MySum where
    pure = MySum
    (MySum f) &lt;*&gt; (MySum a) = MySum (f a)
  
  instance Num a =&gt; Num (MySum a) where
    (+) = liftA2 (+)
    (-) = liftA2 (-)
    (*) = liftA2 (*)
    negate = fmap negate
    abs = fmap abs
    signum = fmap signum
    fromInteger = pure . fromInteger
  </code></pre>