Question

(defun rep(list)
(format t"~a~%" list)
    (cond
        ((null list) nil)
        ((atom (car list)) (cons (car list) (rep  (cdr list))))
        ((listp (car list))  (cons (car (reverse (car list))) (cdr list)))
        (t (rep list))
    )
)

Write a function to replace each sublist of a list with its last element. A sublist is an element from the first level, which is a list. Example:

(a (b c) (d (e (f)))) ==> (a c (e (f))) ==> (a c (f)) ==> (a c f)
     (a (b c) (d ((e) f))) ==> (a c ((e) f)) ==> (a c f)

I have the above problem to solve. Got it till one point but I'm stuck. Apparently it doesn't go to the next elements in the list and I don't know why. Any ideas?

Was it helpful?

Solution 2

Did it without using map functions

(defun rep(list)
    (cond
        ((null list) nil)
        ((listp (car list)) (rep (cons (car (reverse (car list))) (rep (cdr list)))))
        (t (cons (car list) (rep (cdr list))))
    )
)

OTHER TIPS

I would break it down like this:

(defun last-element (lst)
  (if (listp lst)
    (last-element (car (last lst)))
    lst))

(defun rep (lst)
  (when lst
    (cons (last-element (car lst)) (rep (cdr lst)))))

then

(rep '(a (b c) (d (e (f)))))
=> '(A C F)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top