Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala — negation of a predicate [duplicate]

Tags:

scala

Possible Duplicate:
How to use / refer to the negation of a boolean function in Scala?

I'm currently taking Martin Odersky's Scala course in coursera. In one of the assignments, I need to work with the negation of a function (which represents a predicate).

def fun1 (p: Int => Boolean): Boolean = {
/* some code here */
}

Assume the function literal p: Int => Boolean represents some kind of a predicate like x => x > 0

def fun2 (p: Int => Boolean): Boolean = {
val x = fun1 (p)
val y = ???
/* How can I call the negation of the predicate 'p' here? */
return x && y
}

For example, If I call fun2 as fun2 (x => x > 0)

I gave it a lot of thought, but I'm not making any progress with it. I'm not asking for the solution to any of the assignment problems (I'm sticking to the honor code, I believe), but any explanation of what I'm missing here will be of great help.

like image 669
Raj Avatar asked Sep 05 '25 03:09

Raj


1 Answers

You want to write a function that takes a predicate as argument and returns another predicate.

def negate(pred: Int => Boolean): Int => Boolean =
  (x: Int) => !pred(x)
like image 56
user515430 Avatar answered Sep 07 '25 19:09

user515430