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)))
Zachary Beane wrote:
(defun mapcar-pos+ (list)
(let ((i -1))
(mapcar #'(lambda (elt) (+ elt (incf i)))
Truly abysmal ignorance or willful stupidity.
The #' is redundant.
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)))
Gauche Scheme:
| Sysop: | Amessyroom |
|---|---|
| Location: | Fayetteville, NC |
| Users: | 74 |
| Nodes: | 6 (0 / 6) |
| Uptime: | 27:38:32 |
| Calls: | 1,026 |
| Files: | 1,332 |
| D/L today: |
4 files (26K bytes) |
| Messages: | 290,775 |