Pascal's triangle: Difference between revisions

(→‎{{header|AppleScript}}: Slight simplification - closure by direct nesting)
Line 1,142:
'(1)
(cons (+ (car l) (cadr l)) (newrow (cdr l)))))</lang>
 
An iterative solution with ''loop'', using ''nconc'' instead of ''collect'' to keep track of the last ''cons''. Otherwise, it would be necessary to traverse the list to do a ''(rplacd (last a) (list 1))''. Notice we add ''(list 1)'' and not '''(1)'', or this last ''cons'' would be the same for all lists, and modifying one would affect all of them.
 
<lang lisp>(defun pascal-next-row (a)
(loop :for q :in a
:and p = 0 :then q
:as s = (list (+ p q))
:nconc s :into a
:finally (rplacd s (list 1))
(return a)))
 
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
:collect a))</lang>
 
=={{header|D}}==
Anonymous user