【问题标题】:How to specify tuple type in anonymous functions in scala如何在scala的匿名函数中指定元组类型
【发布时间】:2016-09-26 16:52:40
【问题描述】:

我有一个函数叫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

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

【问题讨论】:

  • fold_tree 定义是什么?
  • 抱歉,不小心包含了 map_tree。将其替换为 fold_tree。

标签: scala tree functional-programming tuples


【解决方案1】:

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

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

您收到编译错误,因为您使用了 f2 参数,例如三元组(元组)。相反,您需要像这样的函数参数( (a, b, c) => c )

【讨论】:

  • f2的函数参数是一个元组吧?那么def right_most [A](t:Tree[A]) : A = fold_tree((x: A) => x) ((v: Tuple3[A,A,A]) => v._3) (t) 怎么也没有通过
  • @VarunPatro ...函数参数不能用作元组
猜你喜欢
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
相关资源
最近更新 更多