0
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> 
user3313834
  • 7,327
  • 12
  • 56
  • 99
  • 3
    I believe you understand that `f a b c` calls `f` passing three arguments. `f 2 g 3` similarly passes three arguments. – chi May 22 '21 at 16:28
  • 2
    For the same reason you would need `f(2, g(3))` instead of `f(2, g, 3)` using more traditional function call syntax. – chepner May 22 '21 at 16:53

1 Answers1

4
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.

Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • `Prelude> ((f 2) g)) 3` and `Prelude> ((f 2) g) 3)` return both error: parse error on input ‘)’ – user3313834 May 22 '21 at 16:53
  • 1
    is this a question? `(` and `)` need of course to be balanced – Random Dev May 22 '21 at 17:03
  • sorry I mean in your example they are balanced `Prelude> ((f 2) g) 3` but return `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` – user3313834 May 22 '21 at 17:07
  • 1
    Yes, of course. It's just that `((f 2) g) 3` more clearly demonstrates _why_ that error is happening. (Or perhaps it'd be clearer with `(f 2 g) 3`. – Louis Wasserman May 22 '21 at 17:09
  • @user3313834 I did not try to fix your issue (I think you have a working version right up in the question) - I hoped the problem might be more obvious with the parentheses in. – Random Dev May 22 '21 at 17:27
  • I got it now g is not int – user3313834 May 22 '21 at 19:16