One of the advantages of not handling collections through indices is to avoid off-by-one errors. That's certainly not the only advantage, but it is one of them.
Now, I often use sliding
in some algorithms in Scala, but I feel that it usually results in something very similar to the off-by-one errors, because a sliding
of m
elements in a collection of size n
has size n - m + 1
elements. Or, more trivially, list sliding 2
is one element shorter than list
.
The feeling I get is that there's a missing abstraction in this pattern, something that would be part sliding
, part something more -- like foldLeft
is to reduceLeft
. I can't think of what that might be, however. Can anyone help me find enlightenment here?
UPDATE
Since people are not clear one what I'm talking, let's consider this case. I want to capitalize a string. Basically, every letter that is not preceded by a letter should be upper case, and all other letters should be lower case. Using sliding
, I have to special case either the first or the last letter. For example:
def capitalize(s: String) = s(0).toUpper +: s.toSeq.sliding(2).map {
case Seq(c1, c2) if c2.isLetter => if (c1.isLetter) c2.toLower else c2.toUpper
case Seq(_, x) => x
}.mkString