Slide - what does withPartial do?

Seb seb at wilzba.ch
Thu Mar 1 14:53:14 UTC 2018


On Thursday, 1 March 2018 at 08:31:05 UTC, Piotr Mitana wrote:
> For some reason this is true:
>
> slide!(Yes.withPartial)([1, 2, 3, 4, 5], 3).array == [[1, 2, 
> 3], [2, 3, 4], [3, 4, 5]]
>
> Shouldn't it rather return [[1], [1, 2], [1, 2, 3], [2, 3, 4], 
> [3, 4, 5], [4, 5], [5]], or at least [[1, 2, 3], [2, 3, 4], [3, 
> 4, 5], [4, 5], [5]]?
>
> I can see no difference on the result when withPartial is on 
> and off.
>
> Is it a bug or I don't understand it correctly?

No it's not a bug.
Yes.withPartial (the default) means that if the last element in 
the range doesn't have the full size it still gets printed, with 
No.withPartial it's not part of the range.
It's gets clearer with a different step size:

---
foreach (i; 5 .. 10)
     slide!(Yes.withPartial)(i.iota, 3, 4).writeln;
---


---
[[0, 1, 2], [4]]
[[0, 1, 2], [4, 5]]
[[0, 1, 2], [4, 5, 6]]
[[0, 1, 2], [4, 5, 6]]
[[0, 1, 2], [4, 5, 6], [8]]
---


---
foreach (i; 5 .. 10)
     slide!(No.withPartial)(i.iota, 3, 4).writeln;
---

---
[[0, 1, 2]]
[[0, 1, 2]]
[[0, 1, 2], [4, 5, 6]]
[[0, 1, 2], [4, 5, 6]]
[[0, 1, 2], [4, 5, 6]]
---

https://run.dlang.io/is/x8Q5x8

In fact for the default step size of 1, this only has effect if 
the windowSize is larger than the range size.
BTW as a recent addition to std.range, it comes with a ton of 
unittests:

https://github.com/dlang/phobos/blob/master/std/range/package.d#L7755

(though I agree that the public documentation could explain 
No.withPartial better.)

> > Shouldn't it rather return [[1], [1, 2], [1, 2, 3], [2, 3, 4],
> [3, 4, 5], [4, 5], [5]], or at least [[1, 2, 3], [2, 3, 4], [3, 
> 4, 5], [4, 5], [5]]?


That wouldn't be a sliding window / rolling window operator.
The idea of a sliding / rolling window operator is that all 
windows have the same size. withPartial just allows you to pick 
the behavior for how the final element.

That's also how other languages implement this.
For examples, here's how sliding from Scala's standard library 
behaves:

---
(1 to 5).iterator.sliding(6).withPartial(false).toList // List()
(1 to 5).iterator.sliding(6).withPartial(true).toList //
List(List(1, 2, 3, 4, 5))


(1 to 5).iterator.sliding(3, 4).withPartial(false).toList // 
List(List(1, 2, 3))
(1 to 5).iterator.sliding(3, 4).withPartial(true).toList // 
List(List(1, 2, 3), List(5))
---

https://scastie.scala-lang.org/pR5pH6DRTWuiVR7GNUTbJA


More information about the Digitalmars-d-learn mailing list