How would be a functional approach to shifting certain array elements?

后端 未结 9 2052
感动是毒
感动是毒 2021-01-05 07:03

I have a Scala app with a list of items with checkboxes so the user select some, and click a button to shift them one position up (left). I decided to write a function to sh

9条回答
  •  隐瞒了意图╮
    2021-01-05 07:37

    Here's a purely functional implementation

    def shiftElements[A](l: List[A], pred: A => Boolean): List[A] = {
      def aux(lx: List[A], accum: List[A]): List[A] = {
        lx match {
          case Nil => accum
          case a::b::xs if pred(b) && !pred(a) => aux(a::xs, b::accum)
          case x::xs => aux(xs, x::accum)
        }
      }
      aux(l, Nil).reverse
    }
    

    And here's one that uses mutability on the inside to be faster

    import scala.collection.mutable.ListBuffer
    def shiftElements2[A](l: List[A], pred: A => Boolean): List[A] = {
      val buf = new ListBuffer[A]
      def aux(lx: List[A]) {
        lx match {
          case Nil => ()
          case a::b::xs if pred(b) && !pred(a) => {
            buf.append(b)
            aux(a::xs)
          }
          case x::xs => {
            buf.append(x)
            aux(xs)
          }
        }
      }
      aux(l)
      buf.toList
    }
    

提交回复
热议问题