How to apply pattern match when needed to match a middle element of a Seq() in scala

48 Views Asked by At

This is kind of a learning question rather than a programming code, I have a Sequence as below,

val inputSeq = Seq("A","B","C","D","E")

so I want to identify an inside element (in this case "C") from the sequence using pattern matching and apply pattern matching as in the following example to add an element,

val modified = inputSeq match {

case first_part +: "C" +: tail => first_part +: "C" +: "D" +: tail
case _ => ???
}

I know there are other ways that I can use without pattern matching. However, I want to know how I can achieve this using pattern matching. However, I can't match the first_part as a sequence, can someone help me to find a way to match the first_part as a sequence?

1

There are 1 best solutions below

0
Leo C On

Probably not exactly what you're aiming at, but here's one way to do it by pattern matching recursively:

val inputSeq = Seq("A","B","C","D","E")

def modifyList(seq: Seq[String], s: String, t: String): List[String] = {
  @scala.annotation.tailrec
  def loop(ls: List[String], res: List[String]): List[String] = ls match {
    case Nil => res.reverse
    case `s` :: tail => loop(tail, t :: s :: res)
    case h :: tail => loop(tail, h :: res)
  }
  loop(seq.toList, Nil)
}

modifyList(Seq("A","B","C","D","E"), "C", "D")
// List(A, B, C, D, D, E)

modifyList(Seq("A","B","C","D","E","C","F"), "C", "X")
// List(A, B, C, D, X, E, C, X, F)

Note that the above sample code simply appends to every occurrence of the string being matched against (i.e. s) with the provided string t.