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 shift elements of some arbitrary type which meet a given predicate. So, if you have these elements:
a b c D E f g h I
and the predicate is "uppercase characters", the function would return this:
a b D E c f g I h
In short, any sequence of contiguous elements that meet the predicate are swapped with the single element at the left of it.
I came up with the following ugly imperative implementation. I would like to see a nice, and hopefully readable, functional solution.
def shiftUp[T](a:Array[T], shiftable: T => Boolean) = {
val s = new Array[T](a.length)
var i = 0
var j = 0
while(i < a.length)
{
if(!shiftable(a(i)) && i < a.length - 1 && shiftable(a(i+1)))
{
var ii = i + 1
while(ii < a.length && shiftable(a(ii)))
{
s(j) = a(ii)
ii = ii+1
j = j+1
}
s(j) = a(i)
i = ii
}
else
{
s(j) = a(i)
i = i+1
}
j = j+1
}
s
}
EDIT: Thanks all, I hope you have enjoyed the exercise!