Page 1 of 1
Get last element of a list
Posted: Sun Sep 27, 2009 5:22 am
by daimous
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!
Re: Get last element of a list
Posted: Mon Sep 28, 2009 6:47 pm
by nuntius
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
Posted: Sat Nov 07, 2009 6:36 am
by Wolfgang Tsafack
@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]!)
Re: Get last element of a list
Posted: Sat Nov 07, 2009 12:56 pm
by nuntius
or simply
Code: Select all
(mapcan #'last '((4 5 6) (d e f) (h i j) (5 5 5 5)))
Re: Get last element of a list
Posted: Sat Nov 07, 2009 10:28 pm
by methusala
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)
Re: Get last element of a list
Posted: Sun Nov 08, 2009 4:28 am
by Wolfgang Tsafack
(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
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