Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Ex. 3.5 in ACL

7 views
Skip to first unread message

Robert L.

unread,
Mar 16, 2018, 6:38:00 PM3/16/18
to
Jock Cooper wrote:

> > 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)
> >
> > This is easy to solve using recursion, but the function shall also be
> > defined using iteration and using mapcar.
> >
> > My solutions are as follows, but they horribly and senselessly use
> > side-effects and thus look very inelegant. Is there a better way to do
> > it? (I mean, using just very primitive means - this exercise is in the
> > very beginning of the book...)
> >
> > Thanks!
> >
> > Chris
> >
> > mapcar:
> >
> > (defun pos+1 (lst)
> > (setf i 0)
> > (mapcar #'(lambda (x) (let ((new (+ x i)))
> > (progn (setf i (+ i 1))
> > new)))
> > lst))
> >
>
> You're indeed right that some of your side effects are unneeded.
>
> (defun pos+1 (lst &aux (pos -1))
> (mapcar #'(lambda (val) (+ val (incf pos))) lst))
>
> Most people don't like using &aux; I think for a short function like
> this it's OK.
>
>
> > 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)
>
> (defun pos+ (lst)
> (do* ((pos 0 (1+ pos))
> (lst-cdr lst (cdr lst-cdr))
> (lst-car #1=(car lst-cdr) #1#)
> result)
> ((null lst-cdr) (nreverse result))
> (push (+ pos lst-car) result)))
>
> my preferred way would use LOOP:
>
> (defun pos+ (lst)
> (loop for val in lst
> for pos upfrom 0
> collect (+ val pos)))

(require srfi/42) ; list-ec

(define (pos+ lst)
(list-ec (:list x (index i) lst) (+ x i)))

(pos+ '(200 300 400 500))
===>
'(200 301 402 503)

--
Then the White farmers sought refuge in a police station. The blacks followed
them into the police station and seized them while the black policemen ...
refused to intervene.... Then the blacks stood ... Stevens beside the road and
killed him with shotgun blasts.... http://archive.org/details/nolies
0 new messages