简体   繁体   English

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

[英]How to specify tuple type in anonymous functions in scala

I have a function called map_tree as follows: 我有一个名为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) )
  }

and I need to implement a function called right_most that takes a Tree[A] and returns A . 并且我需要实现一个名为right_most的函数,该函数接受Tree[A]并返回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无法推断吗?

Scala compiler can infer lot of things for you. Scala编译器可以为您推断很多事情。 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). 由于使用f3参数(例如三元组(元组)),因此出现编译错误。 Instead you need function params like this ( (a, b, c) => c ) 相反,您需要这样的函数参数( (a, b, c) => c )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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