Operations on Lists (Iterators & Amend) · General · Practice Question
Remove Consecutive Duplicates from a List
Question
Given:
l:`a`a`a`a`b`c`c`a`a`d`e`e`e`eRemove 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`eSolution
l where differ lExplanation
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
10001101011000bwhere 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).