简体   繁体   中英

Recursively iterate through a Scala list

I'm trying to recursively iterate through a list in Scala using pattern matching. I cannot use any list functions, or while/for loops. What I need to do is iterate through the list, and remove an element if it matches to be '4'. I'm new to Scala and I cannot find the answer in the textbook I have nor on google. Everyone else uses the filter method, or some other list method.

Here's what I tried to do (which is wrong)

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
}

See if this works for you.

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 )
  }
}

Usage:

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

Using an inner function and pattern matching to de-structure the list. If the head in the list is 4 , then do not add it to the accumulator. If it is, append it to the accumulator.

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())
}

The preferred way to do this is with guards in the pattern match but the if else statement may look more familiar if you're just getting started with 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())
}

I am not sure about the execution time. I am also new to scala but I am taking bollean approach to filter any list.

object Main extends App {
//fun that will remove 4
  def rm_4(lst: List[Int]) : List[Int] = {
    val a = lst.filter(kill_4)
    a
  }
// boolean fun for conditions
  def kill_4(n: Int) : Boolean = {
    if (n ==4) false
    else true
  }
println(rm_4(List(1,2,4,5,4))) // outpur List(1,2,5)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM