Gao Gao - 4 years ago 146
Scala Question

Why this example of fpinscala works?(no argument name)

all:
I'm a newbie to scala. I'm not quite understanding an example of curry in the book "functional programming in scala".
Why a function without variables like a, b can be compiled and run smoothly?

def curry[A,B,C](f: (A, B) => C): A => (B => C) =
a => b => f(a, b)

Answer Source

In Scala parameterName => body is an anonymous function that takes a parameter named parameterName and whose body is body.

So a => b => f(a,b) is a function with the parameter a and the body b => f(a,b), which is itself a function with the parameter b and the body f(a,b). In that body a and b are defined because they're parameters.

If that makes it less confusing for you, we can rewrite this using named functions instead:

def curry[A,B,C](f: (A, B) => C): A => (B => C) = {
  def f1(a: A) = {
    def f2(b: B) = f(a,b)
    f2
  }
  f1
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download