Page 1 of 1

couple of lisp questions

Posted: Wed Nov 23, 2011 11:36 pm
by surfy
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

Re: couple of lisp questions

Posted: Thu Nov 24, 2011 6:28 am
by Indecipherable
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)

Re: couple of lisp questions

Posted: Thu Nov 24, 2011 7:15 am
by edgar-rft
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

Re: couple of lisp questions

Posted: Thu Nov 24, 2011 10:56 am
by surfy
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.

Re: couple of lisp questions

Posted: Thu Nov 24, 2011 11:12 am
by virex
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.