Pascal's triangle: Difference between revisions
Content added Content deleted
(Emacs Lisp -- Pascal's triangle) |
(added two variants) |
||
Line 1,892: | Line 1,892: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
===Using mapcar and append, returing a list of rows=== |
|||
<lang lisp>(defun next-row (row) |
<lang lisp>(defun next-row (row) |
||
(mapcar* #'+ (cons 0 row) |
(mapcar* #'+ (cons 0 row) |
||
Line 1,912: | Line 1,913: | ||
(1 4 6 4 1) |
(1 4 6 4 1) |
||
(1 5 10 10 5 1)) |
(1 5 10 10 5 1)) |
||
</pre> |
|||
===Translation from Pascal=== |
|||
<lang lisp>(defun pascal (r) |
|||
(dotimes (i r) |
|||
(let ((c 1)) |
|||
(dotimes (k (+ i 1)) |
|||
(princ (format "%d " c)) |
|||
(setq c (/ (* c (- i k)) |
|||
(+ k 1)))) |
|||
(terpri)))) |
|||
</lang> |
|||
{{Out}} |
|||
From the REPL: |
|||
<pre> |
|||
ELISP> (princ (pascal 6)) |
|||
1 |
|||
1 1 |
|||
1 2 1 |
|||
1 3 3 1 |
|||
1 4 6 4 1 |
|||
1 5 10 10 5 1 |
|||
</pre> |
|||
===Returning a string=== |
|||
Same as the translation from Pascal, but now returning a string. |
|||
<lang lisp>(defun pascal (r) |
|||
(let ((out "")) |
|||
(dotimes (i r) |
|||
(let ((c 1)) |
|||
(dotimes (k (+ i 1)) |
|||
(setq out (concat out (format "%d " c))) |
|||
(setq c (/ (* c (- i k)) |
|||
(+ k 1)))) |
|||
(setq out (concat out "\n")))) |
|||
out)) |
|||
</lang> |
|||
{{Out}} |
|||
Now, since this one returns a string, it is possible to insert the result in the current buffer: |
|||
<pre> |
|||
(insert (pascal 6)) |
|||
1 |
|||
1 1 |
|||
1 2 1 |
|||
1 3 3 1 |
|||
1 4 6 4 1 |
|||
1 5 10 10 5 1 |
|||
</pre> |
</pre> |
||