GHC fails to infer types of certain valid mutually recursive bindings
Summary
User TophatEndermite on Reddit posted the following program and asked why GHC can't infer its type:
f = g 5 + g "hi"
g x = f * 0
This produces the following error:
T.hs:3:7: error:
• No instance for (Num String) arising from the literal ‘5’
• In the first argument of ‘g’, namely ‘5’
In the first argument of ‘(+)’, namely ‘g 5’
In the expression: g 5 + g "hi"
|
3 | f = g 5 + g "hi"
| ^
But it should be quite easy to see that these bindings can be given sensible types:
f :: Integer
g :: a -> Integer
I thought the monomorphism restriction could be causing the inference failure, but turning it off doesn't help.
I also thought the Num
constraint could be causing the failure, but even this program without constraints fails to be inferred by GHC:
plusInt :: Int -> Int -> Int
plusInt = (+)
timesInt :: Int -> Int -> Int
timesInt = (*)
zero :: Int
zero = 0
five :: Int
five = 5
f = plusInt (g five) (g "hi")
g x = timesInt f zero
Why can't GHC infer the types of f
and g
?
Environment
- GHC version used: 9.2.4