5

In ghci, if I do

Prelude> :t 5
Prelude> 5 :: Num a => a

But if I assign 5, I get Integer as the type:

Prelude> let f = 5
Prelude> t: f
Prelude> f :: Integer

From my understanding, the fact that 5 is Num a => a allows is to sit in any mathematical expression happily (such as 5 + 5.0). I guess I'm curious if this is Haskell magic, or whether I can make a variable f that behave the same way, so that I can do f + 5.0. I've tried the following with no luck:

let f = 10 :: Num a => a

f + 5.0 still gives me an error.

  • 2
    It's the "dreaded" monomorphism restriction that makes `f` have type `Integer` in your first example. I'm surprised the explicit polymorphic type doesn't work, but I can't check right now. – Robin Zigmond Jul 10 '19 at 17:40
  • 7
    @RobinZigmond You need to give the type to `f`, not its definition to work. `let f :: Num a => a ; f = 10`. Otherwise, you are giving `10` its own type, which is a no-op -- later on it will still be instantiated following the DMR. – chi Jul 10 '19 at 18:38
  • thanks @chi, that makes sense, I don't think I realised that the annotation was given to the literal `10` rather than the variable `f`. – Robin Zigmond Jul 10 '19 at 22:10

0 Answers0