Currying Example in Scala - scala

Is the following a good example of currying?
def sum(a: Int, b: Int) : (Int => Int) = {
def go(a: Int) : Int = {
a + b;
}
go
}
I half understand the below results, but how could I write (or maybe how I should've written) sum() in a curried way?
scala> sum(3,4) res0: Int => Int = <function1>
scala> sum(3,4).apply(2) res1: Int = 6
scala> sum(3,4).apply(3) res2: Int = 7

Currying mechanism was introduced in Scala to support type inference. For example foldLeft function in the standard lib:
def foldLeft[B](z: B)(op: (B, A) => B): B
Without currying you must provide types explicitly:
def foldLeft[B](z: B, op: (B, A) => B): B
List("").foldLeft(0, (b: Int, a: String) => a + b.length)
List("").foldLeft[Int](0, _ + _.length)
There are three ways to write a curried function:
1) Write it in currying form:
def sum(a: Int)(b: Int) = a + b
which is just syntactic sugar for:
def sum(a: Int): Int => Int = b => a + b
2) Call curried on the function object (sum _).curried and check the types:
sum: (a: Int, b: Int)Int
res10: Int => (Int => Int) = <function1>
In your example, you can use Scala type inference to reduce the amount of code and change your code:
def sum(a: Int, b: Int) : (Int => Int) = {
def go(a: Int) : Int = {
a + b;
}
go
}
into:
def sum(a: Int, b: Int) : (Int => Int) = c => a + b + c
semantically these are the same, because you explicitly provided the return type, so Scala knows that you will return a function wich takes an Int argument and return an Int
Also a more complete answer about curring was given by retronym

In the lambda calculus, you have something called a lambda abstraction λx.term1 which when applied to another term (λx.term1)(term2), corresponds to the concept of applying a function to term2. The lambda calculus is the theoritical basis for functional programming. In lambda calculus, you don't have lambda abstraction taking multiple parameters. So how you do you represent functions of two arguments? The answer is to return a function that will take the other argument and then return the result on both argument.
So in Scala, if you have a var a in scope, you can return a function that will add its argument b to a:
scala> var a = 1
a: Int = 1
scala> val adda = (b: Int) => a + b
adda: Int => Int = <function1>
scala> adda(3)
res1: Int = 4
Now if you have an argument a in scope it works just as well:
scala> val sum = (a: Int) => (b: Int) => a + b
sum: Int => Int => Int = <function1>
scala> sum(3)(5)
res2: Int = 8
So without having access to a syntax that lets you define a function of two arguments, you just basically achieve that with a function sum taking an argument a returning a function equivalent to adda that takes a argument b and returns a + b. And that's called currying.
As an exercise, define a function using currying that will let you work on 3 arguments. For instance val sum3: Int => Int => Int => Int = ???, and fill in what goes into the question marks.

Disclaimer: I'm pretty new to Scala, so treat this with a grain of salt
In purely functional languages like Haskell currying plays very important role in function composition, e.g. if I want to find sum of squares I would write in Haskell (sorry for too much Haskell, but syntax has similarities with Scala and it's not that hard to guess)
without currying:
sum_of_squares xs = foldl (\x y -> x + y) 0 (map (\x -> x * x) xs)
with curring (. is a function composition):
sum_of_squares = (foldl (\x y -> x + y) 0) . (map (\x -> x * x))
which allows me to operate with functions instead of operating with arguments. It may not be that clear from previous example, but consider this:
sum_of_anything f = (foldl (\x y -> x + y) 0) . (map f)
here f is an arbitrary function and I can rewrite the first example as:
sum_of_squares = sum_of_anything (\x -> x * x)
Now let's go back to Scala. Scala is OO language, so usually xs will be a receiver:
def sum_of_squares(xs: List[Int]): Int = {
xs.map(x => x * x).foldLeft(0)((x, y) => x + y)
}
sum_of_squares(List(1,2,3))
def sum_of_anything(f: (Int, Int) => Int)(xs: List[Int]): Int = {
xs.map(x => x * x).foldLeft(0)(f)
}
sum_of_anything((x, y) => x + y)(List(1, 2, 3))
which means I can't omit xs. I can probably rewrite it with lambdas, but I won't be able to use map and foldLeft without adding more boilerplate. So as other people mentioned in Scala "currying" is probably mostly used to support type inference.
Meanwhile in your particular example I have a feeling that you don't need outer a, it's shadowed anyway, you probably meant:
def sum(b: Int) : (Int => Int) = {
def go(a: Int) : Int = {
a + b;
}
go
}
But in this simple example you can use partial application (given that you will probably pass sum to higher order functions):
List(1, 2, 3).map(sum(2)) //> res0: List[Int] = List(3, 4, 5)
List(1, 2, 3).map(_ + 2) //> res1: List[Int] = List(3, 4, 5)
For this kind of application sum can be shorter because sum(2) will be implicitly expanded to Int => Int:
def sum(b: Int)(a: Int): Int = a + b
This form is not valid for val sum2 = sum(2) though, you will have to write val sum2 = sum(2) _.

Related

Is it possible to declare return type for closure?

I'm learning closure in scala programming language.
For example:
val a = (x:Int, y:Int) => x + y;
a(1, 2)
will give me 3. the closure a works like a function (Int, Int):Int.
Is it possible to declare the return type for closure like this ?
val a = (x:Int, y:Int):Int => x + y;
a(1, 2)
Is it possible ?
This syntax is impossible (val a = (x:Int, y:Int):Int => x + y), but you can declare type for a:
val a: (Int, Int) => Int = (x, y) => x + y

Transform Tuples to Array of Points

Suppose I have a class Point with two properties x and y and k tuples:
val p1 = (1,2)
val p2 = (3,4)
val p3 = (33,3)
val p4 = (6,67)
.
.
val p4 = (3,8)
I want to write a function which I can call like:
val arrayOfPoints = tupleToArray(p1,p2,..,pk)
And it will return Array of Points with
x = first value of the tuple and
y = 2nd value of the tuple.
Note: the number of arguments for the function can be any integer >=1.
If we define Point as a case class, we can turn a (Int, Int) tuple into a Point using Point.tupled.
We can accept a variable number of arguments using the variable arguments notation (Int, Int)*.
A function to turn tuples into Points could look like :
case class Point(x: Int, y: Int)
def tupleToPoints(pairs: (Int, Int)*) =
pairs.map(Point.tupled).toArray
scala> tupleToPoints(p1, p2, p3, p4)
res2: Array[Point] = Array(Point(1,2), Point(3,4), Point(33,3), Point(6,67))
If you have a group of points, you can do :
val points = List(p1, p2, p3, p4)
tupleToPoints(points: _*)
Some extra explanation about Point.tupled:
When you call Point(1, 1), you actually call Point.apply(1, 1). If we check the type of Point.apply, we can see it takes two Ints and returns a Point.
scala> Point.apply _
res21: (Int, Int) => Point = <function2>
In your case we have a tuple (Int, Int) which we would like to turn into a Point. The first idea could be pattern matching :
(1, 1) match { case (x, y) => Point(x, y) }
def tupleToPoints(pairs: (Int, Int)*) =
pairs.map { case (x, y) => Point(x, y) }.toArray
// nicer than map(p => Point(p._1, p._2))
But what if we want to use the tuple directly to create a Point using Point.apply, so we don't need this step ? We can use tupled :
scala> (Point.apply _).tupled
res22: ((Int, Int)) => Point = <function1>
We now have a function which takes a tuple (Int, Int) (instead of two Ints) and returns a Point. Because Point is a case class, we can also use Point.tupled which is exactly the same function :
scala> Point.tupled
res23: ((Int, Int)) => Point = <function1>
We can pass this function in our map :
def tupleToPoints(pairs: (Int, Int)*) =
pairs.map(Point.tupled).toArray
// analogous to map(p => Point.tupled(p))

One argument referencing another in the argument list

Occasionally, I encounter one argument wanting to reference another. For instance,
def monitor(time: Double, f: Double => Double, resolution: Double = time / 10) = {...}
Note that resolution refers to time. Are there languages where this is possible? Is it possible in Scala?
It is somewhat possible in Scala, but you have to curry the parameters:
def monitor(time: Double, f: Double => Double)(resolution: Double = time / 10)
You cannot do it in the way the question is posed.
I don't know any langage where this construction is possible, but a simple workaround is not difficult to find.
In scala, something like this is possible :
scala> def f(i : Int, j : Option[Int] = None) : Int = {
| val k = j.getOrElse(i * 2)
| i + k
| }
f: (i: Int, j: Option[Int])Int
scala> f(1)
res0: Int = 3
scala> f(1, Some(2))
res1: Int = 3
In scala, you can also make something like this :
scala> def g(i : Int)(j : Int = i * 2) = i + j
g: (i: Int)(j: Int)Int
scala> g(2)(5)
res6: Int = 7
scala> g(2)()
res7: Int = 6

How to implement generic function in Scala with two argument types?

I'd like to implement a function in Scala that computes the dot product of two numeric sequences as follows
val x = Seq(1,2,3.0)
val y = Seq(4,5,6)
val z = (for (a <- x; b <- y) yield a*b).sum
scala> z : Double = 90.0
val x = Seq(1,2,3)
val y = Seq(4,5,6)
val z = (for (a <- x; b <- y) yield a*b).sum
scala> z : Int = 90
Notice that if the two sequences are of different types, the result is an Double. If the two sequences are of the same type (e.g. Int), the result is an Int.
I came up with two alternatives but neither meets the requirement as defined above.
Alternative #1:
def dotProduct[T: Numeric](x: Seq[T], y: Seq[T]): T = (for (a <- x; b <- y) yield implicitly[Numeric[T]].times(a, b)).sum
This returns the result in the same type as the input, but it can't take two different types.
Alternative #2:
def dotProduct[A, B](x: Seq[A], y: Seq[B])(implicit nx: Numeric[A], ny: Numeric[B]) = (for (a <- x; b <- y) yield nx.toDouble(a)*ny.toDouble(b)).sum
This works for all numeric sequences. However, it always return a Double, even if the two sequences are of the type Int.
Any suggestion is greatly appreciated.
p.s. The function I implemented above is not "dot product", but simply sum of product of two sequences. Thanks Daniel for pointing it out.
Alternative #3 (slightly better than alternatives #1 and #2):
def sumProduct[T, A <% T, B <% T](x: Seq[A], y: Seq[B])(implicit num: Numeric[T]) = (for (a <- x; b <- y) yield num.times(a,b)).sum
sumProduct(Seq(1,2,3), Seq(4,5,6)) //> res0: Int = 90
sumProduct(Seq(1,2,3.0), Seq(4,5,6)) //> res1: Double = 90.0
sumProduct(Seq(1,2,3), Seq(4,5,6.0)) // Fails!!!
Unfortunately, the View Bound feature (e.g. "<%") will be deprecated in Scala 2.10.
You could create a typeclass that represents the promotion rules:
trait NumericPromotion[A, B, C] {
def promote(a: A, b: B): (C, C)
}
implicit object IntDoublePromotion extends NumericPromotion[Int, Double, Double] {
def promote(a: Int, b: Double): (Double, Double) = (a.toDouble, b)
}
def dotProduct[A, B, C]
(x: Seq[A], y: Seq[B])
(implicit numEv: Numeric[C], promEv: NumericPromotion[A, B, C])
: C = {
val foo = for {
a <- x
b <- y
} yield {
val (pa, pb) = promEv.promote(a, b)
numEv.times(pa, pb)
}
foo.sum
}
dotProduct[Int, Double, Double](Seq(1, 2, 3), Seq(1.0, 2.0, 3.0))
My typeclass-fu isn't good enough to eliminate the explicit type parameters in the call to dotProduct, nor could I figure out how to avoid the val foo inside the method; inlining foo led to compiler errors. I chalk this up to no having really internalized the implicit resolution rules. Maybe somebody else can get you further.
It's also worth mentioning that this is directional; you couldn't compute dotProduct(Seq(1.0, 2.0, 3.0), Seq(1, 2, 3)). But that's easy to fix:
implicit def flipNumericPromotion[A, B, C]
(implicit promEv: NumericPromotion[B, A, C])
: NumericPromotion[A, B, C] =
new NumericPromotion[A, B, C] {
override def promote(a: A, b: B): (C, C) = promEv.promote(b, a)
}
It's also worth mentioning that your code doesn't compute a dot product. The dot product of [1, 2, 3] and [4, 5, 6] is 4 + 10 + 18 = 32.

Scala: Defining a function to be the correct type

I've been playing around with Scala code and have come up against a compiler error which I don't understand. The code generates a vector of pairs of Ints and then tries to filter it.
val L = for (x <- (1 to 5)) yield (x, x * x)
val f = (x: Int, y: Int) => x > 3
println(L.filter(f))
The compiler complains about trying to use f as an argument for the filter method with the compiler error message being:
error: type mismatch;
found : (Int, Int) => Boolean
required: ((Int, Int)) => Boolean
How do I define the function f correctly to satisfy the required function type? I tried to add extra parentheses around (x: Int, y: Int) but this gave:
error: not a legal formal parameter
val f = ((x: Int, y: Int)) => x > 3
^
f has type Function2[Int, Int, Boolean]. L's type is IndexedSeq[Tuple2[Int, Int]] and so filter expects a function of type Function1[Tuple2[Int, Int], Boolean]. Every FunctionN[A, B, .., R] trait has a method tupled, which returns a function of type Function1[TupleN[A, B, ..], R]. You can use it here to transform f to the type expected by L.filter.
println(L.filter(f.tupled))
> Vector((4,16), (5,25))
Alternatively you can redefine f to be a Function1[Tuple2[Int, Int], Boolean] as follows and use it directly.
val f = (t: (Int, Int)) => t._1 > 3
println(L.filter(f))
> Vector((4,16), (5,25))
val f = (xy: (Int, Int)) => xy._1 > 3
println (L.filter (f))
If you do
val f = (x: Int, y: Int) => x > 3
you define a function which takes two ints, which is not the same as a function which takes a pair of ints as parameter.
Compare:
scala> val f = (x: Int, y: Int) => x > 3
f: (Int, Int) => Boolean = <function2>
scala> val f = (xy: (Int, Int)) => xy._1 > 3
f: ((Int, Int)) => Boolean = <function1>
If you don't want to rewrite your function to explicitely useing Tuple2 (as suggested by missingfaktor and user unknown), you can define a implicit method to do it automatically. This lets the function f untouched (you aren't forced to always call it with a Tuple2 parameter) and easier to understand, because you still use the identifiers x and y.
implicit def fun2ToTuple[A,B,Res](f:(A,B)=>Res):((A,B))=>Res =
(t:(A,B)) => f(t._1, t._2)
val L = for (x <- (1 to 5)) yield (x, x * x)
val f = (x: Int, y: Int) => x > 3
val g = (x: Int, y: Int) => x % 2 > y % 3
L.filter(f) //> Vector((4,16), (5,25))
L.filter(g) //> Vector((3,9))
f(0,1) //> false
f((4,2)) //> true
Now every Function2 can also be used as a Function1 with an Tuple2 as parameter, because it uses the implicit method to convert the function if needed.
For functions with more than two parameters the implicit defs looks similiar:
implicit def fun3ToTuple[A,B,C,Res](f:(A,B,C)=>Res):((A,B,C))=>Res =
(t:(A,B,C)) => f(t._1, t._2, t._3)
implicit def fun4ToTuple[A,B,C,D,Res](f:(A,B,C,D)=>Res):((A,B,C,D))=>Res =
(t:(A,B,C,D)) => f(t._1, t._2, t._3, t._4)
...