使用尾递归和匹配表达式删除列表中所有出现的元素

Remove all occurrences of element in 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)

这是一个伪代码,只对第一次出现有效。有人可以指导我如何做到这一点,以便消除所有事件吗? 伪代码

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

你的第二个模式不是递归的,实际上它在第一次匹配时以整个尾巴结束递归。

进一步提示:您正在以相反的顺序构建累加器,您可以避免最终使用 :+ 反转它以追加 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))

根据 jwvh 评论,这应该更快

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))
import scala.annotation.tailrec
object Zad3lab04 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) => helper(tail, acc)
        case _ => acc
      }
    }
    helper(l)
  }
  print(remove(List(2, 1, 4, 1, 3, 3, 1, 2), 1))
}

这行得通,以不同的顺序打印列表,如果有人知道为什么可以告诉我。但它工作得很好。