Currying functions in Java
def check( x: Int, y: Int) (z: Int) = {
x+y+z
} //> check: (x: Int, y: Int)(z: Int)Int
def curried = check _ //> curried: => (Int, Int) => Int => Int
def z = curried(0,0) //> z: => Int => Int
z(3) //> res0: Int = 3
check(1,2)(3) //> res1: Int = 6
check(1,2)(_) //> res2: Int => Int = <function1>
I have this code in Scala and I am trying to do this to test it.
check(1,2)
without a third parameter to trigger the check in three ways.
check(1,2)(3) // with three parameters
z(3) // with just one and
check(1,2) with two parameters.
How do I do this in Scala and Java? Can I declare z as implicit in Java? Thank you in advance.
+3
source to share
1 answer
def check( x: Int, y: Int) (z: Int)
When you use the syntax sugars above to create curry functions, you must use _
assign a partially applied function to the value. This way, you don't call the function, but instead create the function value.
val z = curried(0,0) _
However, if you don't use syntactic sugar:
def check( x: Int, y: Int) = (z:Int) => x+y+z
Then you can call it whatever you want:
check(1,2) //res2: Int => Int = <function1>
z(3) // res3: Int = 6
check(1,2)(3) // res4: Int = 6
Note that you do not need to use _
to, for example, pass the result of a partially applied function as a parameter to another function.
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
if (xs.isEmpty) xs
else if (p(xs.head)) xs.head :: filter(xs.tail, p)
else filter(xs.tail, p)
def modN(n: Int)(x: Int) = ((x % n) == 0)
filter(List(1,2,3,4,5), modN(2)) //res6: List[Int] = List(2, 4)
+2
source to share