Get last element of a list

Discussion of Common Lisp
Post Reply
daimous

Get last element of a list

Post by daimous » Sun Sep 27, 2009 5:22 am

Hi Guys! help please..How can i get the last element of a list with a list? say i have a list

Code: Select all

((4 5 6) (d e f) (h i j) (5 5 5 5)) )
how can i have the last element so that my out put would be
(6 f j 5)
Thanks in advance!

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Get last element of a list

Post by nuntius » Mon Sep 28, 2009 6:47 pm

Treasure hunt: You can use two functions from the following lists.
(apropos "last" :cl)
(apropos "map" :cl)

More details can be found in the HyperSpec. A good search tool is at
http://lispdoc.com/

Or see the quick reference at
http://clqr.berlios.de/

Wolfgang Tsafack
Posts: 12
Joined: Thu Nov 05, 2009 11:09 am

Re: Get last element of a list

Post by Wolfgang Tsafack » Sat Nov 07, 2009 6:36 am

@daimous

You need to use mapcar in combination wiht the lambda-function. it's the best way to solve your problem!

Code: Select all

(defun getAllLastElems(listOfLists)
     (mapcar (lambda (list-elem)
                        (last list-elem)
                  ) listOfLists)
)
just try it. I don't know if the function (last list) is correct. If it isn't, try to found a function that return you the last
element of a simple list and replace it with the function last in this code (with the same argument. Don't change the name [list-elem]!)

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Get last element of a list

Post by nuntius » Sat Nov 07, 2009 12:56 pm

or simply

Code: Select all

(mapcan #'last '((4 5 6) (d e f) (h i j) (5 5 5 5)))

methusala
Posts: 35
Joined: Fri Oct 03, 2008 6:35 pm

Re: Get last element of a list

Post by methusala » Sat Nov 07, 2009 10:28 pm

Code: Select all

(defun mylast(x)
       (if (and (listp x) (null (cdr x)) ) (car x)
       (mylast (cdr x))))

(defun eachlast(x)
        (if (null x) x
	    (progn      
 	    (cons (mylast (car x))
       	    (eachlast (cdr x))))))

CL-USER> (eachlast '((1 9 5)(3 3 3)(1 0 3 0 2)))
(5 3 2)

Wolfgang Tsafack
Posts: 12
Joined: Thu Nov 05, 2009 11:09 am

Re: Get last element of a list

Post by Wolfgang Tsafack » Sun Nov 08, 2009 4:28 am

(defun getAllLastElems(listOfLists)
(mapcar (lambda (list-elem)
(last list-elem)
) listOfLists)
)
Hello, I make an error when writing this last post. The function last return a list not a value

Code: Select all

(last '(a d 6)) --> (6)
So you have to add first/or car into the lambda-function. So the correct code is show below:
(defun getAllLastElems(listOfLists)
(mapcar (lambda (list-elem)
(car (last list-elem))
) listOfLists)
)
That work effiziently.

@methusala
That was also a good idea solving the problem. But too long for me.

all have a good day

Post Reply