Nested Loops Using Loop Macro in Common Lisp
Asked Answered
P

1

3

I am trying to implement a basic nested loop in CL, but the Loop macro is resisting this. Basically, I would like to find all possible products of 3-digit numbers and accumulate them into a list.

Here is my attempt:

 (loop for x downfrom 999 to 998 do (loop for y downfrom 999 to 998 collect (* x y)))

The code above returns NIL for some reason. By the way, I realize that I only run down to 998, but this is done for testing purposes.

What could I do to obtain a list like this:

(999*999 999*998 ... 998*998 998*997 ... 997*997 997*996 ... 100*100)

Phonics answered 25/11, 2016 at 20:45 Comment(1)
Peter Seibel gives an overview of LOOP: gigamonkeys.com/book/loop-for-black-belts.htmlKirby
H
11

The COLLECT-clause in the inner loop doesn't affect the outer loop. So the inner loop returns a list of results, but the DO-clause in the outer loop just discards the result. You should use APPEND or NCONC instead of DO. Usually it's better to just stick with APPEND if there are no performance concerns, even if in this case NCONC would be safe.

(loop for x downfrom 999 to 900
      append (loop for y downfrom 999 to 900
                   collect (* x y)))
Hemorrhage answered 25/11, 2016 at 20:56 Comment(4)
Magic! Much appreciated!Phonics
I am still getting used to reading CL's docs and they can be confusing at times.Phonics
@Phonics w.r.t. the CLHS LOOP pages, that's a mild understatement, isn't it. :)Tibbitts
@WillNess Yes, a mild one haha :-)Phonics

© 2022 - 2024 — McMap. All rights reserved.