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

后端 未结 9 2106
感动是毒
感动是毒 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条回答
  •  梦毁少年i
    2021-01-05 07:38

    You could probably do this via a foldLeft (also known as /:):

    (str(0).toString /: str.substring(1)) { (buf, ch) =>
        if (ch.isUpper) buf.dropRight(1) + ch + buf.last  else buf + ch
    }
    

    It needs work to handle the empty String but:

    def foo(Str: String)(p: Char => Boolean) : String = (str(0).toString /: str.substring(1)) { 
       (buf, ch) => if (p(ch) ) buf.dropRight(1) + ch + buf.last else buf + ch
    }
    
    val pred = (ch: Char) => ch.isUpper
    foo("abcDEfghI")(pred) //prints abDEcfgIh
    

    I'll leave it as an exercise as to how to modify this into the array-based solution

提交回复
热议问题