Tuple2错误地推断为递归Scala函数中的Product

时间:2013-05-08 14:36:42

标签: scala type-inference

我有一个函数可以从Tuple2 [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 = 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
               ^

提前致谢。

1 个答案:

答案 0 :(得分:2)

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