Varun Patro Varun Patro - 7 months ago 30
Scala Question

How to specify tuple type in anonymous functions in scala

I have a function called

as follows:

def fold_tree[A,B](f1: A => B) (f2: (A,B,B) => B) (t: Tree[A]) : B = t match {
case Leaf(value) => f1(value)
case Node(value , l, r) => f2 (value, fold_tree (f1) (f2) (l), fold_tree (f1) (f2) (r) )

and I need to implement a function called
that takes a
and returns
. Here's my attempt at it:

def right_most [A](t:Tree[A]) : A =
fold_tree ((x: A) => x) ((v: (A, A, A)) => v._3) (t)

But I get the following errors:

found : ((A, A, A)) => A
required: (A, A, A) => A
fold_tree ((x: A) => x) ((v: (A, A, A)) => v._3) (t)
one error found

Looks to me like found and required are the same. What's the error then? Additionally, how do we specify the tuple type in anonymous functions? And why do I need to specify the tuple type in the function signature. Can't scala infer it?


Scala compiler can infer lot of things for you. so, do this

def right_most [A](t:Tree[A]) : A =
    fold_tree[A, A](_) ((_, _, c) => c) (t)

You got compilation error because you were using f2 params like triplet (tuples). Instead you need function params like this ( (a, b, c) => c )