简体   繁体   中英

How to specify tuple type in anonymous functions in scala

I have a function called map_tree 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 right_most that takes a Tree[A] and returns A . 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM