2016-01-23 142 views
0

我想通过模式匹配递归遍历Scala中的列表。我不能使用任何列表函数,或者使用/ for循环。我需要做的是遍历列表,并删除一个元素,如果它匹配成'4'。我是新来的斯卡拉,我无法在教科书中找到答案,也没有在Google上找到答案。其他人都使用过滤方法或其他列表方法。递归遍历一个Scala列表

这里就是我试图做的(这是错误的)

def removeFours(lst: List[Int]): List[Int] = { 
val newLst = lst 
lst match { 
    case Nil => Nil 
    case a if a == 4 => newLst -= 0 
    case n => removeFours(newLst) 
} 
newLst 
} 

回答

6

看看这对你的作品。

def removeFours(lst: List[Int], acc: List[Int] = List.empty): List[Int] = { 
    lst match { 
    case Nil => acc.reverse 
    case 4 :: t => removeFours(t, acc) 
    case h :: t => removeFours(t, h :: acc) 
    } 
} 

用法:

scala> removeFours(List(3,7,4,9,2,4,1)) 
res84: List[Int] = List(3, 7, 9, 2, 1) 
2

使用一个内部函数和模式匹配脱结构列表。如果列表中的头是4,则不要将其添加到累加器。如果是,请将其附加到累加器。

def removeFours(lst: List[Int]): List[Int] = { 
    def loop(lst: List[Int], acc: List[Int]): List[Int] = lst match { 
    case Nil => acc 
    case h :: t => 
     if (h == 4) { 
     loop(t, acc) 
     }else{ 
     loop(t, acc :+ h) 
     } 
    } 
    loop(lst, List()) 
} 

做到这一点的首选方法是使用模式匹配后卫,但如果else语句可能看起来比较熟悉,如果你是刚刚开始使用Scala。

def removeFours(lst: List[Int]): List[Int] = { 
    def loop(lst: List[Int], acc: List[Int]): List[Int] = lst match { 
    case Nil => acc 
    case h :: t if (h == 4) => loop(t, acc) 
    case h :: t => loop(t, acc :+ h) 
    } 
    loop(lst, List()) 
} 
+0

向'loop'函数添加'@ tailrec'注释以确保它不会堆栈。它不会在这种情况下,但它总是一个很好的做法。 –