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

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

    Edit: this doesn't actually solve the posed problem--it solves a related but different problem (bumping up the priority of marked items by one). I'm leaving it here for reference, however.


    Here's a "one-liner", using arrays as requested, for Scala 2.8.

    def shiftUp[T](a: Array[T], p: T => Boolean) = {
      a.zipWithIndex.map(ci => {
        (ci._1 , if (p(ci._1)) ci._2 - 1.5 else ci._2.toDouble)
      }).sortWith((l,r) => l._2 < r._2).map(_._1)
    }
    
    scala> shiftUp(Array('h','E','l','l','O'),(c:Char)=>c.isUpper).toArray
    res0: Array[Char] = Array(E, h, l, O, l)
    
    scala> shiftUp("HeLlO".toArray,(c:Char)=>c.isUpper).toArray
    res1: Array[Char] = Array(H, L, e, O, l)
    

    I leave it as an exercise to the reader to figure out how it works. (If you really want generics with T, in Scala 2.8 it's going to give you an GenericArray; you then can toArray it if you want a Java potentially-primitive array.)

提交回复
热议问题