List 为什么这个列表是空的
我想在scala中创建一个函数,它使用“match…case”将列表的值加倍 例如:List 为什么这个列表是空的,list,scala,match,List,Scala,Match,我想在scala中创建一个函数,它使用“match…case”将列表的值加倍 例如: doubleList(List(2,1,4,5)) //> res0: List[Int] = List(4, 2, 8, 10) 我写了这个函数: def doubleList(xs: List[Int]): List[Int] = xs match { case y :: ys => y * 2; doubleList(ys); case Nil
doubleList(List(2,1,4,5))
//> res0: List[Int] = List(4, 2, 8, 10)
我写了这个函数:
def doubleList(xs: List[Int]): List[Int] =
xs match {
case y :: ys =>
y * 2; doubleList(ys);
case Nil => xs;
}
但结果我得到了一个空列表:
//> res0: List[Int] = List()
有人能告诉我我做错了什么吗?代码关闭语句并有效地丢弃结果,使用
:
创建一个新的列表
,结果为y*2
和doubleList(ys)
另外,你不必输入
代码>在scala中的一行末尾。
关闭语句并有效地丢弃结果,使用:
创建一个新的列表
,结果为y*2
和doubleList(ys)
另外,你不必输入
代码>在scala中的一行末尾。任何原因,为什么你不直接使用map(*2)
?是的,我被要求具体使用“匹配…案例”。任何原因,为什么你不直接使用map(*2)
?是的,我被要求具体使用“匹配…案例”。哦,我不知道这一点;结束语句。谢谢你的回答,效果很好。哦,我不知道;结束语句。谢谢你的回答,效果很好。
def doubleList(xs: List[Int]): List[Int] =
xs match {
case y :: ys =>
y * 2 :: doubleList(ys)
case Nil => xs
}