Get the last item from each list

Say I have a list ((3 4 5) (d e f) (h i j) (5 5 5 5))

How can I get the last element of each list so that the result looks like this (5 fj 5)?

+5
source share
5 answers

Assuming this is about Common Lisp, there is a last function that returns a list containing the last element of the list. If you use this function with mapcan , which applies this function to each element of the list and returns concatenated results, you will get what you want.

, - O(N), , , , , (, ).

+9

, LISPy, - / . - , .

, -, , :

:

  • '()? ( - null)
  • '(a)? ( - a, , , )
  • '((a))? ( - (a))
  • '(anything), - ? ( - (first anything))
  • '(anything morestuff)? ( - (cons (first anything) (first-element morestuff)))
  • ? , ( ).
  • null? nil.
  • ? (car list)

:

;; here first, meeting questions 6-8
(define first (lambda (l)
  (cond 
    ((null? l) nil) ; Q7
    ((atom? l) l)   ; Q6
    (t (car l)))))  ; Q8

;; with first we can write first-element, meeting questions 1-5
(define first-element (lambda (l)
  (cond
    ((null? l) nil) ; Q1
    ((atom? l) (first l))   ; Q2
    (t (cons (first (car l) (first-element (cdr l)))))))) ; Q4-5

(). , . , , .

MAPCAR? . . MAPCAR. ? . Dang LISP/ , .

, , . " foo ?" : null? ? ? ? , , foo. foo on null? foo ? foo ?

+3

, , MAP (a.k.a. MAPCAR) , - .

0

, ,

; SELECT-FROM-INNER-LIST :: [list] -> [list]
(DEFUN SFIL (lst)
  (COND ((NULL lst) NIL)
        ((LISTP (FIRST lst)) (APPEND (LAST (FIRST lst)) (SFIL (REST lst))))
))

Now this works for a legitimate list ... so if you call the SFIL function with the correct list .... if not, it will return NIL

I hope it will be useful for those who find it

0
source
(defun get-last-lists (s)
    (setq rt 'nil)
    (loop for i from 0 to (- (length s) 1)
        do (setq rt (append rt (last (nth i s)))))
    (print rt))

as a newbie to lisp, I submit my solution.

0
source

All Articles