This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Get last element of a list

6 posts · 7683 views

Hi Guys! help please..How can i get the last element of a list with a list? say i have a list
((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!

Re: Get last element of a list

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/

Re: Get last element of a list

@daimous

You need to use mapcar in combination wiht the lambda-function. it's the best way to solve your problem!
(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]!)

Re: Get last element of a list

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

Re: Get last element of a list

(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)

Re: Get last element of a list

(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
(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