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

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

    Here's another variant on Geoff's answer:

    def shift[T](l: List[T], p: T => Boolean): List[T] = {
      l match {
        case a::b::t if ! p(a) && p(b) => b::shift(a::t, p)
        case a::t => a::shift(t, p)
        case Nil => l
      }
    }
    

    Quickly tested using

    scala> def pred(c: Char) = c.isUpper
    pred: (c: Char)Boolean
    
    scala> shift("abcDEfghI".toList, pred)
    res3: List[Char] = List(a, b, D, E, c, f, g, I, h)
    
    scala> shift("AbCd".toList, pred)
    res4: List[Char] = List(A, C, b, d)
    
    scala> shift(Nil, pred)
    res5: List[Nothing] = List()
    

    Here's version two

    def shift[T](l: List[T], p: T => Boolean, r: List[T] = Nil): List[T] = {
      l match {
        case a::b::t if ! p(a) && p(b) => shift(a::t, p, b::r)
        case a::t => shift(t, p, a::r)
        case Nil => r.reverse
      }
    }
    

提交回复
热议问题