如何在scala中的匿名函数中指定元组类型

时间:2016-09-26 08:28:37

标签: scala tree functional-programming tuples

我有一个名为map_tree的函数,如下所示:

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

我需要实现一个名为right_most的函数,它接受Tree[A]并返回A。这是我的尝试:

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

但我收到以下错误:

 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

在我看来,发现和要求是一样的。那是什么错误?另外,我们如何在匿名函数中指定元组类型?为什么我需要在函数签名中指定元组类型。 scala不能推断它吗?

1 个答案:

答案 0 :(得分:1)

Scala编译器可以为您推断出很多东西。所以,这样做

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

您遇到了编译错误,因为您正在使用像triplet(元组)这样的f2参数。相反,你需要像( (a, b, c) => c )

这样的函数参数
相关问题