Defining function with multiple variables

While defining a function,like:
x => x * x

It means input x would be mapped to x * x

Similarly,
(x,y) => x * y

It means this function takes 2 inputs (x,y) and multiply them.

But how to explain something like this:

y => x/y

Input y is clear, but what’s the origin of x?

It’s a captured variable. It comes from a scope of function definition. For instance:

def times(x: Int, y: Int): Int = {
  def timesX(a: Int): Int = x * a
  timesX(y)
}

This is taken from Coursera’s functional programming course.
In Week 2 lecture, fixed point for a function is determined, as:

def fixedPoint(f: Double => Double)(firstGuess: Double) = {
…body of the function
}
def sqrt(x: Double) = fixedPoint(y => x/y)(1)

So I am not sure what is x in scope of the function here.

PS: I guess origin of y is in question here. x is the number whose square root is to be determined.

If the code compiles (does it?) y must be in scope somehow. It’s
likely defined in some scope that encloses sqrt, or it could be
imported. (There are more possibilities, but they’re even less likely.)

Post the rest of the code; I bet we could find y. Also, this is where
IDEs are helpful: you can click on a symbol and go to its definition.

y is defined as the parameter of the function passed to fixedPoint.

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

You have both x and y defined in this line. x is passed as parameter to sqrt, y is an argument to function passed to fixedPoint. Additionally, that function passed to fixedPoint closes over x from sqrt parameters list.

For more examples look eg here: https://www.tutorialspoint.com/scala/scala_closures.htm (although I spent only seconds googling it; maybe there are better explanations somewhere).

General concept is described here: https://en.wikipedia.org/wiki/Closure_(computer_programming)

1 Like

Oops, duh. No IDE needed - that’s definitely where y comes from.