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

后端 未结 9 2063
感动是毒
感动是毒 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:34

    Not the fastest, but not limited to String and using the same logic as @oxbow_lakes

    def shift[T](iter: Iterable[T])(p: T=>Boolean): Iterable[T] = 
      iter.foldLeft(Iterable[T]())((buf, elm) => 
        if (p(elm) && buf.nonEmpty) 
          buf.dropRight(1) ++ Iterable[T](elm) ++ Iterable[T](buf.last) 
        else 
          buf++Iterable[T](elm)
      )
    
    def upperCase(c:Char)=c.isUpper
    
    shift("abcDEfghI")(upperCase).mkString
        //scala> res86: String = abDEcfgIh
    
    val array="abcDEfghI".toArray
    shift(array)(upperCase).toArray
        //res89: Array[Char] = Array(a, b, D, E, c, f, g, I, h)
    
    def pair(i:Int)=i%2==0
    val l=List(1,2,3,5,4,6,7,9,8)
    shift(l)(pair)
        //scala> res88: Iterable[Int] = List(2, 1, 3, 4, 6, 5, 7, 8, 9)
    

提交回复
热议问题