Addressing parameter function's parameter in a scala method - scala

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

You could make it return a function that does that, like so:
def fun(f: Int => Int, y: Int): Int => Int =
input => if (f(input) > 0) y - 1 else y + 1
val test1 = fun(x => x*2, 1)
println(test1(-1)) // "2"
val test2 = fun(x => x - 100, 5)
println(test2(101)) // "4"
val test3 = fun(x => x, -10)
println(test3(0)) // "-9"
EDIT: Note that I changed the signature of the input function, as I think it probably reflects the requirements better, changing it back to boolean should be trivial(see other answers). :)
EDIT(2):
Seeing is you updated your question, I thought best to update my answer: You can always just inline a function, in your example, maybe you could do it like this:
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))

Your original problem can't be solved because you can't test the output of f() without invoking f(), and you can't invoke f() without an input argument to pass. I think the best you can hope for is something like this.
def fun(f: Int => Boolean, y: Int): Int => Int = (arg: Int) =>
if (f(arg)) y - 1
else y + 1
Your "similar problem" looks to me like it should be a different question.
Your proposed solution can be solved via recursion, but using forall() it can be expressed more concisely.
def exists(s: Set[Int], p: Int => Boolean): Boolean =
!forall(s, (x:Int) => !p(x))

It sounds like you don't actually want to pass a parameter to your anonymous function? Then try this:
def fun(f: () => Boolean, y: Int): Int =
if (f()) y - 1
else y + 1

Related

Why should calling a currying function with non-complete args with underscore

According to ScalaByExample:
A curried function definition def f (args1) ... (argsn) = E where n >
1 expands to
def f (args1) ... (argsn−1) = { def g (argsn) = E ; g }
Or, shorter, using an anonymous function:
def f (args1) ... (argsn−1) = ( argsn ) => E
Uncurried version:
def f(x: Int): Int => Int = {
y: Int => x * y
} //> f: (x: Int)Int => Int
def f1 = f(10) //> f1: => Int => Int
f1(5)
Curried version:
def g(x: Int)(y: Int) = {
x * y
} //> g: (x: Int)(y: Int)Int
def g1 = g(10) _ //> g1: => Int => Int
g1(5)
The question is, Why curried required the underscore in line #5 in the second code snippet.
You can find the explanation at Martin Odersky book: http://www.artima.com/pins1ed/functions-and-closures.html (search for "Why the trailing underscore").
In short this is because Scala is closer to Java in a lot of things, rather than functional languages where this is not required. This helps you to find out mistakes at compile time, if you forgot the missing argument.
If underscore was not required, the next code will compile:
println(g(10))
And this check helps you preventing such mistakes
There are some cases though, when such calls are obvious, and underscore is not required:
def g(x: Int)(y: Int) = {
x * y
}
def d(f: Int => Int) {
f(5)
}
d(g(10)) // No need to write d(g(2) _)
// Or any other way you can specify the correct type
val p: Int => Int = g(10)
Something to note: in Scala, def's are methods, not functions, at least, not directly. Methods are converted to functions by the compiler every time a method is used where a function would be required, but strictly speaking, a function would be created with val instead, like so:
val curry = (x: Int) => (y: Int) => x * y
This allows you to apply arguments one at a time without having to add a trailing underscore. It functions identically to the code in your first snippet, but because it uses val and not def, curry cannot be written like
val curry(x: Int) = (y: Int) => x * y //Won't compile
So, when you want to write a function that behaves the way you want a curried function to behave, write it like I did in my first snippet. You can keep chaining parameters with => as many times as you want (up to technical limits, but good luck hitting them).

Modify function passed as argument

I have two functions. One is masterChecker, wich takes as argument an Int x and a function p, and return the boolean result p(x). Simple like that.
def masterChecker(x: Int, p: Int => Boolean): Boolean = p(x)
Then I have a second function childChecker, which is like an alias to masterChecker
def childChecker(x: Int, f: Int => Boolean): Boolean = masterChecker(x , f)
Is there any way to change f in the masterCheker call on childChecker, in a manner that it would run like !f ? (if f return true, than make it false)
Like:
// inside childChecker
masterChecker(x, !f)
I know that I could do it on the masterChecker call with !masterChecker(x,f), but what I want to know is if it´s possible to change a function behavior passed as an argument.
Sure, you can use an anonymous function like so:
def childChecker(x: Int, f: Int => Boolean) = masterCheck(x, !f(_))
and there you go!
Even more so, you could do a number of things if you want to "modify" f within the function scope of childChecker:
def childChecker(x: Int, f: Int => Boolean) ={
def proxy(x: Int): Boolean ={
val y: Int = //do things
f(y) //see? "y" not "x"
}
masterCheck(x, proxy)
}
that's part of the fun when you're dealing with plain ol' functions. Granted, this "modification" is more of a decorator pattern but it does adhere to the interface.

Scala and Writing map functions

So suppose I have a function that expects a Set with definition Int => Boolean and a function f like this:
def map(s: Set, f: Int => Int): Set = {}
Now how do I apply this f to each element of this set s.
def map(s: Set, f: Int => Int): Set = { (i: Int) => f(s(i)) }
Which is ofcourse incorrect because in f(s(i)), 's(i)' returns a boolean, and thus can't apply f on it. Problem is how do I access each element of Set and apply this f on it?
This question is part of Coursera's Functional Programming with Scala course.
A goal of the course is to help you understand the functional model, and in this case, how the Set can be represented by a function (called the charasteristic function for that set).
Instead of the final solution, here's a hint on how to reason about this problem:
Given the characteristic function f: Int => Boolean that defines your set and x, an Int, if f(x) == true, then x belongs to the Set. Now, if you have a function g:Int=>Int
that you want to map over the set, what you want is to apply that function to the elements that you know that belong to the set: if (f(x)) then g(x).
Try to apply that thinking to your exercise.
If you wrote the exists function correctly:
def map(s: Set, f: Int => Int): Set = (i: Int) => exists(s, (x: Int) => i == f(x))
Bam one line!
You need to use fold to do this.
def map(s: Set[Int], f: Int => Int): Set[Int] =
s.foldLeft(Set.empty[Int])((s,i) => s+f(i))

Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala

I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:
def sum(f: Int => Int) = (a: Int, b: Int) => f(a) + f(b)
def sum2(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
def sum3(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b)
val ho = sum({identity})
val partial = sum2({ identity }, _, _)
val currying = sum3({ identity })
val a = currying(2, 2)
val b = partial(2, 2)
val c = ho(2, 2)
So, if I can calculate partially applied function that easy, what are the advantages of currying?
Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.
using(new File(name)) { f =>
...
}
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.
For instance, if I define a max function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
I can call it like this:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
or even shorter:
max(List(1, -3, 43, 0)) (_ < _)
If I defined max as an uncurried function, this would not work, I'd have to call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.
I think it becomes clearer if you invert your curried example:
def sum4(a: Int, b: Int)(f: Int => Int): Int = f(a) + f(b)
val d = sum4(2, 2) { x =>
x * x
}
It is more of an optical effect but you don’t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don’t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you use
val partial_sum4 = sum4(2, 2)
anywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.
(Well, and there are some advantages with respect to type inference…)

Anonymous recursive function in Scala

Is there a way to write an anonymous function that is recursive in Scala? I'm thinking of something like this:
((t: Tree) => {
print(t.value);
for (c <- t.children)
thisMethod(c)
})(root)
(Related question: Which languages support *recursive* function literals / anonymous functions?)
As described in the link you posted. You can use Y-combinator. Here is example:
scala> def fix[A,B](f: (A=>B)=>(A=>B)): A=>B = f(fix(f))(_)
fix: [A,B](f: ((A) => B) => (A) => B)(A) => B
scala> val fact = fix[Int,Int](f => a => if(a<=0) 1 else f(a-1) * a)
fact: (Int) => Int = <function1>
scala> fact(12)
res0: Int = 479001600
Note it doesn't work with big numbers.
Be careful with tail call optimization.
If you don't want to hit the "Amazing mathematics" you could just revert to the object aspects of scala.
val fact = new Function1[Int,Int]{
def apply(x:Int):Int = if(x==1) x else x * apply(x-1)
}
in order to make it look geekier you can also use this code style:
val fact = new ((Int) => Int){
def apply(x:Int):Int = if(x==1) x else x * apply(x-1)
}
Adding to the many good responses here in this thread, the fact that Scala is not giving us tail call optimizable Fixed-point combinator has been bothering me so much so that I've decided to write a macro to translate Y-combinator-like call to an ordinary, idiomatic recursive call (with tail call optimization, of course). The idea is that a call like
fix[Int,Int]((next) => (y) => ...body...)
is readily translatable into
({(input) =>
object next {
def apply(y:Int):Int = ...body...
}
next(input)
})
I've put up macro implementation targeting Scala 2.11 (with minor tweak should also work with 2.10) into this gist.
With this macro, we can perform ordinary recursive tasks in anonymous manner without fearing stack overflow e.g.
import asia.blip.ymacro.YMacro._
(y[BigInt,BigInt]((xx) => (y) => if(y==1) 1 else y * xx(y-1)))(2000)
gives
res0: BigInt = 33162750924506332411753933805763240382811...
Recursive calls on Scala.
Let me take sum of N numbers example for recursion
var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x}
scala> sumIt(10)
val res141: Int = 55
You can see the sumIt has its type with Int, Int as Input and the return value. The sumIt lambda function takes as argument which is an Integer and it does recursive call on sumIt.
I just this example for easy understanding the recursion call. You can direct formula for this logic like...
sumValue = (N*(N+1)) /2
A very simple approach:
val fact = { (x: Int) =>
def f(x: Int): Int = if (x == 0) 1 else x * f(x-1)
f(x)
}
// Use as anonymous function below
(1 to 5).map { (x: Int) =>
def f(x: Int): Int = if (x == 0) 1 else x * f(x-1)
f(x)
}
// res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 6, 24, 120)