Iterators · Each · Practice Question
Duplicate Each Element in a List
Question
Given:
l:`a`b`c`c`dDuplicate each element in the list to produce:
`a`a`b`b`c`c`c`c`d`dSolution
raze (2#) each lAlternative Solution
raze l,'lAlternative Solution
raze 2#/:lExplanation
(2#) each lapplies the take operator 2# independently to every symbol in l, turning each single symbol into a 2-item list containing it twice:
a a
b b
c c
c c
d draze then flattens that list of lists back into a single flat list.
The alternatives reach the same result with related iterators: l,'l uses each-both (') to join l with itself item by item, and 2#/:l uses each-right (/:) to take 2 of each item on the right. All three demonstrate how closely each, each-both, and each-right are related — they differ only in which side of the function holds the list being iterated over.