couple of lisp questions

Discussion of Common Lisp

couple of lisp questions

Postby 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
surfy
 
Posts: 2
Joined: Wed Nov 23, 2011 11:33 pm

Re: couple of lisp questions

Postby 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 !
User avatar
Indecipherable
 
Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.

Re: couple of lisp questions

Postby 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
edgar-rft
 
Posts: 161
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany

Re: couple of lisp questions

Postby 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.
surfy
 
Posts: 2
Joined: Wed Nov 23, 2011 11:33 pm

Re: couple of lisp questions

Postby 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.
virex
 
Posts: 17
Joined: Fri Oct 28, 2011 3:41 pm


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot], Yahoo [Bot] and 3 guests