[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: Ex. 3.5 in ACL

William James

7/26/2015 7:33:00 PM

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)))

Gauche Scheme:

gosh> (map + '(200 300 400 500) (lrange 0))
(200 301 402 503)

Another way:

gosh> (use gauche.sequence :only (map-with-index))
#<undef>
gosh> (map-with-index + '(200 300 400 500))
(200 301 402 503)

--
Another major theme here is that whereas allegiance to ingroups indicates
psychopathology in gentiles, the epitome of psychological health for the
authors of The Authoritarian Personality is the individualist who is completely
detached from all ingroups, including his or her family.
--- Dr. Kevin MacDonald; "The Frankfurt School of Social Research and the
Pathologization of Gentile Group Allegiances"