Negate Func<int, bool> to return opposite bool

Viewed 46

I have a lambda that returns a function that negates the result for a given function, but I just cannot get it to work.

Example:

not(x => x % 2 == 0)(1) --> true  
not(x => x % 2 == 0)(2) --> false

My current code:

Func<Func<int,bool>, Func<int, bool>> not = y => !y;

Func<int, bool> equalTo0 = x => x == 0;

var test3 = not(equalTo0)(5);

This would return false for example, but with the not lambda it should return true.

Has anyone have any idea/ideas on how to change the outcome of the function?

1 Answers

You are trying to write a lambda that takes a function and returns another function. That returned function can be written as another lambda:

// parentheses not necessary, just for clarity 
Func<Func<int,bool>, Func<int, bool>> not = f => (x => !f(x));

f is the function that is inputted to not, you then return the function x => !f(x).

This can also be written as a generic method:

Func<T, bool> Not<T>(Func<T, bool> f) => x => !f(x);
Related