## couple of lisp questions

Discussion of Common Lisp

### couple of lisp questions

I'm new to LISP...just started...and it is not the easiest language...hopefully someone here knows it.

I have several functions I need to write, and the first one is simply to add an atom (integer) to the last element of the list (all integers).

Test 1:
List is (1 2 3 4), and x is 5
Output should be: (1 2 3 9)

Test 2
List is (1 2 3 (4 5) ), and x is 5
Output should be: (1 2 3 (9 10))

so far I can add a specific atom (number) to all elements in a list like this:

Code: Select all
`(defun addingIt (L num)   ( cond               (   (eq L nil)  nil  )            (   (append  (list (+ (car L) num) )   (addingIt (cdr L) num  ) )  )     ))`

but not to the last element of the list
surfy

Posts: 2
Joined: Wed Nov 23, 2011 11:33 pm

### Re: couple of lisp questions

Please format your code correctly. As for finding the last element of a list, (last) will do the job
(last '(1 2 3))
>>> 3

(last '(1 2 (3 4 5)))
>>> (3 4 5)
Don't take the FUN out of DEFUN !

Indecipherable

Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.

### Re: couple of lisp questions

Indecipherable wrote:As for finding the last element of a list, (last) will do the job...

Sorry, but this is wrong. For finding the last element of a list you need (first (last ...)) because LAST returns the last element in a list:

Code: Select all
`(last '(1 2 3))          => (3)(first (last '(1 2 3)))  => 3(last '(1 2 (3 4 5)))          => ((3 4 5))(first (last '(1 2 (3 4 5))))  => (3 4 5)`

- edgar
edgar-rft

Posts: 91
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany

### Re: couple of lisp questions

yes, i know how to use those list functions, but I don't know how to properly create the correct new list and then return it.
surfy

Posts: 2
Joined: Wed Nov 23, 2011 11:33 pm

### Re: couple of lisp questions

Easiest way would be to let Lisp copy the list for you (say hi to copy-tree) and destructively alter the new list (technically a tree since it can contain sublists, hence the use of copy-tree as opposed to copy-list). |Then just check if the final argument is a cons or a number and handle each case appropriately.
virex

Posts: 17
Joined: Fri Oct 28, 2011 3:41 pm