monta monta - 3 months ago 16
Scala Question

One line Scala function to invert (Int => Boolean) function

Question



If there a way in Scala to define the inv function below in one line?

// Function to invert a decision function such as even/odd/positive/...
def inv(f: Int => Boolean):(Int => Boolean) = {
def g(a:Int):Boolean = {
!f(a)
}
g
}

// Test
def even(x:Int):Boolean = (x % 2 == 0)
val odd = inv(even)
println("odd(99) is %s".format(odd(99)))
----
odd(99) is true


Problem



Tried below with !f or !f(a) as below but got errors. Not sure what exactly is wrong. If explanation can be provided, it would be appreciated.

def inv(f: Int => Boolean):(Int => Boolean) = !f
----
error: value unary_! is not a member of Int => Boolean

def inv(f: a:Int => b:Boolean):(Int => Boolean) = !f(a)
----
error: ')' expected but ':' found.
def inv(f: a:Int => b:Boolean):(Int => Boolean) = !f(a)
^

Answer

You can write

def inv(f: Int => Boolean):(Int => Boolean) = a => !f(a)     

What's wrong with !f: f isn't a Boolean.

What's wrong with def inv(f: a:Int => b:Boolean): When the parser looks at this definition, it knows that f: is going to be followed by a type. a can be a type, but it can't be followed by : in this case (a:Int => b:Boolean is not a type).