0

I am faced with the following problem: I want to be able to modify a mathematical function in a way that you would move it in an x-y-graph. Therefore, I have two variables, x and y, which shall move the function upwards or to the right, respectively.

Let f be a function of type Double => Double, and let x and y be the aforementioned parameters. I want to do this:

def moveGraph(f: Double => Double, x: Double, y: Double): Double => Double = {
    f(_ - x) + y
}

This, however, throws the following compiler error:

Error:(5, 7) missing parameter type for expanded function ((x$1) => x$1.$minus(x))
    f(_ - x) + y
      ^

How can I have _ represent the parameter put into the function passed as f and still operate on it?

Dominik Weitz
  • 120
  • 1
  • 7

3 Answers3

2

Your moveGraph function should look like this:

def moveGraph(f: Double => Double, x: Double, y: Double): Double => Double =
  p => f(p - x) + y

If you want to use the passed in parameter, you have to name it.

The compiler doesn't understand what _ should stand for. Here is a list of all possible usages for _.

Community
  • 1
  • 1
Mifeet
  • 12,949
  • 5
  • 60
  • 108
2

Just adding to Mifeet answer, it is not like you have to name parameters. Just the shorthand notation for anonymous functions is quite simple and just expands in its current scope, so

f(_ - x) + y

becomes

f(param => param - x) + y

This is what compiler did, and complained that it doesn't know the type.

If f would expect a function Int => Int it would be a valid usage.

But you want to do something else here and you need to be explicit about your param

param => f(param - x) + y
Łukasz
  • 8,555
  • 2
  • 28
  • 51
1

A fancier way to do it in scala is using function combinators:

def moveGraph(f: Double => Double, x: Double, y: Double): Double => Double  = 
 {p:Double => p - x } andThen f andThen y.+

((-x).+ andThen f andThen y.+ would be even nicer, but it doesn't' work in this case unfortunately, because + is overloaded, and scala gets confused by it).

Dima
  • 39,570
  • 6
  • 44
  • 70