Sysop: | Amessyroom |
---|---|
Location: | Fayetteville, NC |
Users: | 23 |
Nodes: | 6 (0 / 6) |
Uptime: | 52:39:46 |
Calls: | 583 |
Files: | 1,139 |
D/L today: |
179 files (27,921K bytes) |
Messages: | 111,617 |
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)))