0

When I define a curried function like:

def fx(x: Int) (f: Int => Int): Int = f(x)

I can call it using:

fx(2)(x => x * x)

But cannot call it using:

(fx 2) (x => x * x)

However

If we take the foldLeft fun from scala std library, with signature:

def foldLeft[B](z: B)(f: (B, A) => B): B

I can call it using:

(xs foldLeft 0 ) ( _ + _)

But cannot call it using:

xs foldLeft (0) ( _ + _)

Question:

Why in case if my defined fun, I can call it using f(x)(fx), but cannot call it using (f x)(fx), However in case of foldleft, I can call it using (obj f x)(fx) but cannot call it using obj f (x) (fx) ?

Hint: I know this is because operator precedence, but need detailed answer

Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219
  • This has nothing to do with operator precedence – kiritsuku Aug 15 '15 at 12:56
  • 1
    More or less duplicate of http://stackoverflow.com/questions/1181533/what-are-the-precise-rules-for-when-you-can-omit-parenthesis-dots-braces-f – kiritsuku Aug 15 '15 at 12:57
  • from @Daniel C. Sobral of the question above, I could understand two things (related to my case here), 1. infix works only when on object is part of the equation (hence `(fx 2)` is not valid) 2. in case of curried functions (foldLeft), I have to surround the first infix with parenthesis before applying the send curried argument "I'm not sure the exact rules at play here". But still I need explanation. – Muhammad Hewedy Aug 15 '15 at 13:22

1 Answers1

2

In your example you are not using fx in infix position. A function or operator in infix requires an instance where this function is called on left of the function or operator and an argument to the right.

Example:

(xs foldLeft 0 ) ( _ + _)

foldLeft(infix) is called on xs (left) - which is some Collection - passing 0(right) as argument.

In your example:

(fx 2) (x => x * x)

The object fx is called on is missing. If you change your example a bit, it works:

object someInstance {
  def fx(x: Int)(f: Int => Int): Int = f(x)

  val test = (this fx 2) (x => x * x)
}

// OR
val test2 = (someInstance fx 2) (x => x * x)

It would work.

Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37