It's probably obvious, but it's making me crazy and I think my code is being bloated as a result (missing the obvious, not the making me crazy part).
I have a method as follows:
def fun(f: Int => Boolean, y: Int): Int
This method is going to be called like this fun(*some anon func*, y) and should increase and return y + 1 when some anon function (applied to some param) is greater than 0 and y - 1 otherwise. How to define fun? I'm trying something like
def fun(f: Int => Boolean, y: Int): Int =
if (f) y - 1
else y + 1
Obviously, that doesn't work. I should put f(tmp), where tmp:Int but I'm now sure how to express that.
All examples I could find online always apply f on y, but this is just funny.
Update: here's a similar problem I have already solved, but am not happy with how did I do it:
For a given function forall(s: Set, p: Int => Boolean): Boolean, which returns true iff all the set elements x in S (def S: int => Boolean, indicator function for set S) satisfy p(x), create a function that will implement exists quantifier (exists function). In set theory, one can express this quantifier as (in terms of the problem described above) not all elements (not forall) of a set satisfy NOT p.
I did something like this:
def exists(s: Set, p: Int => Boolean): Boolean = {
def negP(x: Int): Boolean = !p(x)
!forall(s, negP)
}
My question is: how to do this without defining negP? I cannot state !p because Scala gives error for ! operator. I cannot use !p(x) because there is no x. Hence the problem above and my question.
TIA
anon function is greater than 0--f: Int => Booleancannot be compared to0: Int, so probably you should clarify your goals.(x: Int) => x * x, thenywould always go up, no matter what. However, when I pass(x: Int) => x - 2, it will get different results for x <= 2 and for x > 2.