Back to General

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

Remove Consecutive Duplicates from a List

Sign in to track your progress

Question

Given:

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

Remove consecutive duplicates from l — unlike distinct, a value should be kept again if it reappears later after other values, just not while it's repeating in place.

Expected result:

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

Solution

l where differ l

Explanation

differ compares each item of l to the one before it, returning 1b whenever a value is different from its immediate predecessor (the first item is always 1b, since it has no predecessor to differ from):

q)differ l
10001101011000b

where then keeps only the positions where differ is true — the first item of every run of consecutive duplicates, and drops the repeats. Because the second run of as (after c) is treated independently from the first, both runs contribute an a to the result — which is exactly why this isn't the same as distinct l (`a`b`c`d`e, with only one a).