splitBy: to sequence.slate

Brian T. Rice water at tunes.org
Wed Jul 21 00:00:07 PDT 2004


Cool, an SDF user (I live in Seattle and know the guy who runs it). Thanks for
the code. :)

Olli Pietiläinen <ollip at sdf.lonestar.org> said:

> Hi.
> 
> I wrote a small method for sequence.slate:
> 
> s@(Sequence traits) splitBy: n
> "Splits the sequence to n-sized sequences. If size of the sequence is not
> divisible by n, last element will be smaller."
> [| subSeqs sepIndex nextSeq remainder |
>    n <= 0 ifTrue: [error: 'Split size must be positive.'].
>    n > s size ifTrue: [error: 'Split size shouldn\'t be bigger than sequence
size.'].
> 
>    subSeqs: ExtensibleArray newEmpty.
>    sepIndex: 0.
>    [sepIndex < (s size - (s size mod: n))]
>       whileTrue: [ nextSeq: (s copyFrom: sepIndex to: (sepIndex + n) - 1).
>                    subSeqs addLast: nextSeq.
>                    sepIndex: sepIndex + n].
>    sepIndex = s size
>       ifFalse: [ remainder: (s copyFrom: sepIndex to: (s size - 1)).
>                  subSeqs addLast: remainder].
>    subSeqs
> ].

Here's a slightly tweaked version of it:

s@(Sequence traits) splitIntoSize: n
"Answers the result of splitting the sequence into n-sized sequences.
If size of the sequence is not divisible by n, the last element will be
smaller."
[| subSeqs sepIndex nextSeq remainder |
   n isPositive ifFalse: [error: 'Split size must be positive.'].
   n >= s size ifTrue: [^ {s copy}].
   subSeqs: (Array newSize: s size // n + 1) writer.
   sepIndex: 0.
   [sepIndex < (s size - (s size mod: n))]
      whileTrue: [nextSeq: (s copyFrom: sepIndex to: sepIndex + n - 1).
                  subSeqs nextPut: nextSeq.
                  sepIndex: sepIndex + n].
   sepIndex = s size
      ifFalse: [remainder: (s copyFrom: sepIndex to: s indexLast).
                subSeqs addLast: remainder].
   subSeqs contents
].

I added a failure mode where the whole sequence is copied and returned as the
one result if you ask for a larger split-size than what it has, as it's
returning 0 full-size elements and one "fractional".

> I don't know if this is a good name for it. Maybe groupBy: would be better?

src/group.slate actually defines groupBy: to return a Grouping, kind of like
SQL's "group by". splitIntoSize: is what occurred to me. Does that sound right?

> Olli




More information about the Slate mailing list