Scala类型问题:Char to Any

时间:2012-11-01 19:58:02

标签: scala

我试图递归地实现一个方法,但我很困惑,因为在某些时候编译器认为它返回List[List[Any]]而不是List[List[Char]]。这是我的功能:

def anag(wrd: List[Char]): List[List[Char]] = if(wrd.isEmpty) List(wrd)
    else wrd.map(l => l :: anag(wrd.tail)) //found: List[List[Any]]

def anag(wrd: List[Char]): List[List[Char]] = if(wrd.isEmpty) List(wrd)
    else wrd.map(l => l :: wrd.tail) //OK  

我错过了什么?

1 个答案:

答案 0 :(得分:1)

函数anag返回List [List [Char]],你将它与char:

组合
l :: anag(wrd.tail) //prepending a char to a list of List[Char]

第二个例子没问题,因为wrd.tail的类型为List [Char]

编辑: 怎么解决?因为这可能是针对课程的作业,我会留给你。你只需要遍历整个单词和通过递归调用anag返回的所有部分解决方案(查看理解)

您还可以使用scala库中的方法排列查找列表的所有排列:

wrd.permutations.toList