Possible Duplicate:
Inconsistent behaviour for xs.sliding(n) if n is less than size?
EDIT: I realise that the behaviour described here is the expected behaviour of sliding; I'm questioning why this is the case.
EDIT 2: Duplicate of this question
I'm using the sliding function on a scala collection, and I'm surprised by the behaviour in the following case:
m.sliding( N )
where M is m.size, and M < N.
In this case, you don't get back an empty iterator, you get back a single-element iterator, where the only element is the input:
scala> List( ).sliding( 2 ).size
res0: Int = 0
scala> List( 1 ).sliding( 2 ).size
res1: Int = 1
As an example, here's a simple function to recursively calculate a row from Pascal's triangle:
def row( num : Int ) : List[ Int ] =
{
num match
{
case 0 => List( 1 )
case x : Int => List( 1 ) ++ row( x - 1 ).sliding( 2 ).map( _.sum ) :+ 1
}
}
but this doesn't as expected, because of the behaviour discussed above:
scala> row( 1 )
res0: List[Int] = List(1, 1, 1)
Instead, we have to include an extra special case:
def row2( num : Int ) : List[ Int ] =
{
num match
{
case 0 => List( 1 )
case 1 => List( 1, 1 )
case x : Int => List( 1 ) ++ row2( x - 1 ).sliding( 2 ).map( _.sum ) :+ 1
}
}
and this now works as expected.
Does anyone know why sliding behaves like this? It seems strange to me that I ask for sub-collections of a certain length, and in the case discussed here you get a single collection of a different length!