The obvious way to solve the problem is to simply look at each element of the list in turn, and each time it is compared with an equal needle, it takes its position to the output list. Getting a position is very simple in this case, because we start from the beginning of the haystack; we can use a variable to calculate the current position, starting from 0.
So, if we describe the complete algorithm in the sentence, we would say something like "find all the needle positions in the haystack, for each element in the haystack and position, starting from 0, when the element is equal to the needle, collect the position."
The LOOP function is basically the right thing to break out when you want to do iterative processing. Despite the fact that its syntax is more difficult to formally describe after some experience, you can pretty much just put the English-language description of the algorithm in the LOOP body, and it will work.
(defun all-positions (needle haystack)
(loop
for element in haystack
and position from 0
when (eql element needle)
collect position))
source share