Back to General

Operations on Lists (Iterators & Amend) · General · Practice Question

Pack Consecutive Duplicates into Sublists

Sign in to track your progress

Question

Given:

l:`a`a`a`a`b`c`c`a`a`d`e`e`e`e

Pack consecutive duplicates of list elements into sublists.

Expected result:

`a`a`a`a
,`b
`c`c
`a`a
,`d
`e`e`e`e

Solution

(where differ l) cut l

Alternative Solution

st:where l<>prev l
n:neg st - (count l)^next st
l {x + til y}'[st;n]

Alternative Solution

sublist[;l] each flip (st;n)

Explanation

This builds on the same differ trick used to remove consecutive duplicates, but instead of discarding the repeats, it keeps each run grouped together.

q)where differ l
0 4 5 7 9 10

gives the starting index of every run of consecutive duplicates. cut then slices l at exactly those points, so each slice is one unbroken run — `a`a`a`a (indexes 0–3), ,b(index 4), ``cc `` (indexes 5–6), and so on — which is precisely what cut` is for: splitting a list into pieces at a given set of starting positions.

The alternatives compute the same run boundaries (st, the start of each run) and lengths (n, how long each run is) explicitly, then either build each run with {x + til y} (each-both, ') or slice it out directly with sublist.