scala collections : map a list and carry some state?

后端 未结 2 808
广开言路
广开言路 2021-01-14 17:52

I seem to run into this problem all the time. I want to modify some of the elements in a list, but I need to keep some state as I do it, so map doesn\'t work.

Here i

2条回答
  •  终归单人心
    2021-01-14 18:29

    The tricky part is that the "d" and "f" elements get no modification.

    This is what I came up with. It's a bit more concise, code wise, but does involve multiple traversals.

    val l1: List[String] = List("a","b","c","d","e","f","b","c","e","b","a")
    
    l1.reverse.tails.foldLeft(List[String]()){
      case (res, Nil) => res
      case (res, hd::tl) =>
        val count = tl.count(_ == hd)
        if (count > 0) s"$hd${count+1}" +: res
        else if (res.contains(hd+2)) (hd+1) +: res
        else hd +: res
    }
    //res0: List[String] = List(a1, b1, c1, d, e1, f, b2, c2, e2, b3, a2)
    

    By using tails, each element, hd, is able to see the future, tl, and the past, res.

提交回复
热议问题