Search code examples
haskelllazy-evaluationtype-inferencetype-systems

Invalid use of function in Haskell with no type error


https://i.sstatic.net/t3Vlb.png thats the image of the output ^ . the declarations are here:

let add1 x = x + 1
let multi2 x = x * 2
let wtf x = ((add1 multi2) x)
(wtf 3)

<interactive>:8:1:
    No instance for (Num (a0 -> a0)) arising from a use of `it'
    In a stmt of an interactive GHCi command: print it
?>

Can anyone explain to me why Haskell says that the type of the invalid expression is Num and why it wont print the number? I can't understand what is going on on the type system.


Solution

  • add1 multi2 applies add1 to a function, but add1 expects a number. So you might expect this to be an error because functions aren't numbers, but the thing is that they could be. In Haskell a number is a value of a type that's an instance of the Num type class and you can add instances whenever you want.

    That is, you can write instance Num (a -> a) where ... and then functions will be numbers. So now mult2 + 1 will do something that produces a new function of the same type as mult2 (what exactly that will be depends on how you defined + in the instance of course), so add1 mult2 produces a function of type Num a -> a -> a and applying that function to x gives you a value of the same type as x.

    So what the type wtf :: (Num (a -> a), Num a) => a -> a is telling you is "Under the condition that you a is a numeric type and you define an instance for Num (a -> a)", wtf will take a number and produce a number of the same type. And when you then actually try to use the function, you get an error because you did not define an instance for Num (a -> a).