List comprehensions: Difference between revisions

→‎{{header|Common Lisp}}: The loop macro does list comprehension, except with no nested iteration.
(→‎{{header|Common Lisp}}: The loop macro does list comprehension, except with no nested iteration.)
Line 234:
 
=={{header|Common Lisp}}==
Common Lisp's <tt>loop</tt> macro has all of the features of list comprehension, except for nested iteration. <tt>(loop for x from 1 to 3 for y from x to 3 collect (list x y))</tt> only returns <tt>((1 1) (2 2) (3 3))</tt>. You can nest your macro calls, so <tt>(loop for x from 1 to 3 append (loop for y from x to 3 collect (list x y)))</tt> returns <tt>((1 1) (1 2) (1 3) (2 2) (2 3) (3 3))</tt>.
Common Lisp doesn't have list comprehensions built in, but we can implement them easily with the help of the <code>iterate</code> package.
 
Here are the Pythagorean triples:
 
<lang lisp>(defun pythagorean-triples (n)
(loop for x from 1 to n
append (loop for y from x to n
append (loop for z from y to n
when (= (+ (* x x) (* y y)) (* z z))
collect (list x y z)))))</lang>
 
CommonWe Lispcan doesn'talso havedefine lista comprehensionsnew builtmacro in,for butlist comprehensions. weWe can implement them easily with the help of the <code>iterate</code> package.
 
<lang lisp>(defun nest (l)
Line 260 ⟶ 271:
(for z from y to n)
(when (= (+ (expt x 2) (expt y 2)) (expt z 2)))))</lang>
 
 
=={{header|D}}==
Anonymous user