1

I was going through videos of Functional Programming in Scala taught in coursera. I came across these code

def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2

and its implementation as

  def sqrt(x: Double): Double = fixedPoint(averageDamp(y => y / x))(1)

but couldn't use it in the form

  averageDamp(x => x)

It says that argument is missing. Isn't the argument missing in above case as well. Somebody help. Thanks in advance :)

pramesh
  • 1,914
  • 1
  • 19
  • 30
  • Partial application of multiple parameter list methods is only possible (a) explicitly (like `averageDamp(x => x) _`) or (b) implicitly in a functional context (like `val f: Double => Double = averageDamp(x => x)`). My guess is that `fixedPoint` requires `Double => Double`, so we have option (b) – Victor Moroz Aug 13 '16 at 12:43

1 Answers1

0

The keyword for this is currying. When averageDamp defined as above, averageDamp will expect two parameters. When you write it with only first paramater it will return a functional (closure) which takes another argument. Thats why it says argument is missing when you call it like averageDamp(x => x). You just calling a function without parameter which expects one. To actually evaluate the value you should call it like averageDamp(some_function)(double_value).

Checkout this: http://www.codecommit.com/blog/scala/function-currying-in-scala

alpert
  • 4,500
  • 1
  • 17
  • 27
  • `When you call it with first parameter it will return a function (closure)` this part is wrong. You can't call it with only first parameter (technically first **parameter list** here), unless you are in a functional context and Scala knows you expect a function, and what is missing is a complete parameter list. – Victor Moroz Aug 13 '16 at 17:23
  • You are right calling is not the correct verb here. – alpert Aug 13 '16 at 18:35
  • I was calculating the square root. Still cannot use as: averageDamp(y => x/y)(1) – pramesh Jul 26 '17 at 15:37