One line Scala function to invert (Int => Boolean) function -
question
if there way in scala define inv function below in 1 line?
// function invert decision function such 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) %s".format(odd(99))) ---- odd(99) true problem
tried below !f or !f(a) below got errors. not sure wrong. if explanation can provided, appreciated.
def inv(f: int => boolean):(int => boolean) = !f ---- error: value unary_! not member of int => boolean def inv(f: a:int => b:boolean):(int => boolean) = !f(a) ---- error: ')' expected ':' found. def inv(f: a:int => b:boolean):(int => boolean) = !f(a) ^
you can write
def inv(f: int => boolean):(int => boolean) = => !f(a) what's wrong !f: f isn't boolean.
what's wrong def inv(f: a:int => b:boolean): when parser looks @ definition, knows f: going followed type. a can type, can't followed : in case (a:int => b:boolean not type).
Comments
Post a Comment