1

我有一个从 Tuple2 [Char,Int] 列表创建组合的函数。

但是,当我对其进行递归调用时,会出现编译错误,元组被推断为产品。

为什么会这样,我怎样才能让它编译?

这是代码示例

这编译OK: -

Welcome to Scala version 2.10.1 (OpenJDK 64-Bit Server VM, Java 1.7.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def combos(a: List[(Char,Int)]): List[List[(Char,Int)]] = {
     |     if(a.isEmpty) List(List()) else {
     |       {
     |         for{
     |           x <- 0 to a.length
     |           (char,num) <- a take x
     |           rest = a drop x
     |           less <- num to 1 by -1           
     |         } yield (char,less) :: rest
     |       } toList
     |     }
     |   }
warning: there were 1 feature warning(s); re-run with -feature for details
combos: (a: List[(Char, Int)])List[List[(Char, Int)]]

但是这个递归失败了..看到底部的错误

Welcome to Scala version 2.10.1 (OpenJDK 64-Bit Server VM, Java 1.7.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def combos(a: List[(Char,Int)]): List[List[(Char,Int)]] = {
     |     if(a.isEmpty) List(List()) else {
     |       {
     |         for{
     |           x <- 0 to a.length
     |           (char,num) <- a take x
     |           rest = combos(a drop x)
     |           less <- num to 1 by -1          
     |         } yield (char,less) :: rest
     |       } toList 
     |     }
     |   }
<console>:17: error: type mismatch;
 found   : List[List[Product]]
 required: List[List[(Char, Int)]]
             } toList
               ^

提前致谢。

4

1 回答 1

2

rest 的类型(组合的结果)是List[List[(Char,Int)]]并且您正在附加(Char,Int),因此常见的推断类型是Product. 也许你的意思是rest <- combos(a drop x)

于 2013-05-08T14:52:32.723 回答