couple of lisp questions

Discussion of Common Lisp
Post Reply
surfy
Posts: 2
Joined: Wed Nov 23, 2011 11:33 pm

couple of lisp questions

Post by surfy » Wed Nov 23, 2011 11:36 pm

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

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

Re: couple of lisp questions

Post by Indecipherable » Thu Nov 24, 2011 6:28 am

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 !

edgar-rft
Posts: 226
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany

Re: couple of lisp questions

Post by edgar-rft » Thu Nov 24, 2011 7:15 am

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

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

Re: couple of lisp questions

Post by surfy » Thu Nov 24, 2011 10:56 am

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.

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

Re: couple of lisp questions

Post by virex » Thu Nov 24, 2011 11:12 am

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.

Post Reply