I am just trying to solve Ex 3.5 in Graham's ANSI Common Lisp book. I am reading it on my own and not as part of a university course. The task is:
define a function pos+, that takes a list as param and returns a list
that adds the position of each element of the list to the element's value. Thus:
(pos+ '(7 5 1 4))
returns:
(7 6 3 7)
...but it's also easy with DO:
(defun do-pos+ (orig-list)
(do ((i 0 (1+ i))
(list orig-list (cdr list))
(new-list nil (cons (+ (car list) i) new-list)))
((endp list) (nreverse new-list))))
(defun mapcar-pos+ (list)
(let ((i -1))
(mapcar #'(lambda (elt) (+ elt (incf i)))
iteration:
(defun pos+ (lst)
(setf acc NIL)
(setf i 0)
(dolist (obj lst)
; i know, instead of append, i could do a cons and reverse afterwards...
(progn (setf acc (append acc (list (+ obj i))))
(setf i (+ i 1))))
acc)
I'd prefer LOOP here:
(defun loop-pos+ (list)
(loop for i from 0
for elt in list
collect (+ elt i)))
B. Pym wrote:
(defun mapcar-pos+ (list)
(let ((i -1))
(mapcar #'(lambda (elt) (+ elt (incf i)))
iteration:
(defun pos+ (lst)
(setf acc NIL)
(setf i 0)
(dolist (obj lst)
; i know, instead of append, i could do a cons and reverse afterwards...
(progn (setf acc (append acc (list (+ obj i))))
(setf i (+ i 1))))
acc)
I'd prefer LOOP here:
(defun loop-pos+ (list)
(loop for i from 0
for elt in list
collect (+ elt i)))
(defun pos+ (xs)
(do ((i 0 (+ 1 i))
r)
((not xs) (reverse r))
(push (+ i (pop xs)) r)))
| Sysop: | Amessyroom |
|---|---|
| Location: | Fayetteville, NC |
| Users: | 54 |
| Nodes: | 6 (1 / 5) |
| Uptime: | 21:47:26 |
| Calls: | 742 |
| Files: | 1,218 |
| D/L today: |
6 files (8,794K bytes) |
| Messages: | 186,234 |
| Posted today: | 1 |