Is it possible to declare return type for closure? - scala

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

Related

scala convert Int => Seq[Int] to Seq[Int => Int]

Is there a convenient way to convert a function with type Int => Seq[Int] to Seq[Int => Int] in scala?
For example:
val f = (x: Int) => Seq(x * 2, x * 3)
I want to convert it to
val f = Seq((x: Int) => x * 2, (x: Int) => x * 3)
Generally, it is impossible.
For example, you have a function x => if (x < 0) Seq(x) else Seq(x * 2, x * 3). What is the size of the Seq that your hypothetical function will return?
As #ZhekaKozlov has pointed out, collections are going to be a problem because the type is the same no matter the size of the collection.
For tuples, on the other hand, the size is part of the type so you could do something like this.
val f1 = (x: Int) => (x * 2, x * 3) //f1: Int => (Int, Int)
val f2 = ((x:Int) => f1(x)._1, (y:Int) => f1(y)._2) //f2: (Int => Int, Int => Int)
Not exactly a "convenient" conversion, but doable.

Define recursive lambda expression in scala

I am trying to define a recursive lambda expression in scala and struggling a bit with sintax, if think that this is just a syntax:
Here is what I have so far (not compilable):
type rec = (Int => Int, Int)
val f = (x : Int) => x + x
val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1
Error I am getting:
ScalaFiddle.scala:14: error: ScalaFiddle.rec does not take parameters
val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1
^
Original code sample I am trying to optimize (which works fine):
case class Rec[I, O](fn : (I => O, I) => O) extends (I => O) {
def apply(v : I) = fn(this, v)
}
val sum = Rec[Int, Int]((f, v) => if (v == 0) 0 else v + f(v - 1))
Any help would be appreciated.
Thanks
rec is a tuple of type Tuple2[Int => Int,Int].
in your statement val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1, you are trying to call a apply function on the tuple y (y(f,1)). Since the tuple doesnt have a apply function defined you are getting the error rec does not take parameters
as per your sample code your type rec (Int => Int, Int) => Int.
so the code sample would be
type rec = (Int => Int, Int) => Int
val f = (x : Int) => x + x
val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1
Check This link for this answer explanation
var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x

scala list of anonymous functions

Like to create a list of function literals and (a) avoid pre-defining them and (b) use shorthand syntax. Failing at the moment.
def g = (x: Int) => x + 1 //pre-defined
def h = (x: Int) => x + 2
List(g,h) //succeeds
List( (x: Int) => x + 1, (x: Int) => x + 2) ) //fails
^';' expected but ')' found.
Please clarify, do you know types of your functions in advance?
If yes, then you can explicitly specify type of your list:
# List[Int=>Int](x => x + 1, x => x + 2)
res20: List[Int => Int] = List(<function1>, <function1>)
Or even shorter:
# List[Int=>Int](_ + 1, _ + 2)
res21: List[Int => Int] = List(<function1>, <function1>)
If you want List type to be inferred, try following syntax:
# List({ x: Int => x + 1}, { x: Int => x + 2 })
res22: List[Int => Int] = List(<function1>, <function1>)

Currying Example in 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) _.

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)
...