haskellhaskell-prelude

why does function combine require parantesis in haskell?


Prelude> -- I have 2 functions: f and g
Prelude> f x y = x + y
Prelude> g x = 2*x
Prelude> f 2 3
5

To express $ f(x, g(y))* with x=2 and y=3 this work well:

Prelude> f 2 (g 3)
8

why does the following return error ?

Prelude>
Prelude> f 2 g 3

<interactive>:19:1: error:
    • Non type-variable argument in the constraint: Num (a -> a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num a, Num (a -> a)) => a
Prelude> 

Solution

  • f 2 g 3
    

    is (because function application left-associative):

    f 2 g 3 = ((f 2) g) 3
    

    that's why you get this error - it expects g there to be a Num (as it is the parameter y in f x y = x+y and + :: Num a -> a -> a -> a)

    2 as a literal can be a value in every Num a but GHC does not know a instance for Num that is a function a -> a.

    Now the error itself talks about the context - basic Haskell cannot have a constraints of the form Num ((->) a a) - but you could easily (and safely) circumvent this with the given extension ... then you should get the error with the type-class.