Search code examples
scalatail-recursion

Remove all occurrences of element in list using Tail Recursion and Match expression


The task is to remove all occurrences of element in a list using Tail Recursion and Match expression.

remove(List(2, 1, 4, 1, 3, 3, 1, 2), 1), should return : List(2, 4, 3, 3, 2)

This is a pseudocode, which works only for the first occurance. Can someone guide me how to do it so it would remove all occurances? pseudocode

import scala.annotation.tailrec
object Test extends App{
  def remove[A](l: List[A], el: A): List[A] = {
    @tailrec
    def helper(l: List[A], acc: List[A] = List[A]()): List[A] = {
      l match {
        case head :: tail if (head != el) => helper(tail, head::acc)
        case head :: tail if (head == el) => (acc.reverse ::: tail)
        case _ => acc
      }
    }
    helper(l)
  }
  print(remove(List(2, 1, 4, 1, 3, 3, 1, 2), 1))
}

Solution

  • Your second pattern is not recursive, indeed its ending the recursion with the entire tail at the first match.

    Further hint: you are building the accumulator in the reverse order, you can avoid the need to eventually reverse it with :+ to append in queue

    def remove[A](l: List[A], el: A): List[A] = {
      @tailrec
      def helper(l: List[A], acc: List[A] = List[A]()): List[A] = {
        l match {
          case head +: tail => helper(tail, if(head != el) acc:+head else acc)
          case _ => acc
        }
      }
    
      helper(l)
    }
    print(remove(List(2, 1, 4, 1, 3, 3, 1, 2), 1))
    

    as per jwvh comments this should be faster

    import scala.annotation.tailrec
    
    def remove[A](l: List[A], el: A): List[A] = {
      @tailrec
      def helper(l: List[A], acc: List[A] = List[A]()): List[A] = {
        l match {
          case head +: tail => helper(tail, if(head != el) head+:acc else acc)
          case _ => acc.reverse
        }
      }
    
      helper(l)
    }
    print(remove(List(2, 1, 4, 1, 3, 3, 1, 2), 1))