N
N
Nikita Kolosov2012-11-26 02:19:32
Lisp
Nikita Kolosov, 2012-11-26 02:19:32

Getting a list of atoms of a given S-expression

I decided to study Lisp, I found a textbook, lectures on the Internet, I sit, I understand.

Actually, I found a job:

Write a function that returns a list of atoms from a given S-expression in the same order that they appear in it.
Example:
> (atoms '((ab) c nil (d (efg))))
(ABC NIL DEFG)


Posted by
(DEFUN atoms (x)
  (COND 
    ((NULL x) NIL)
    ((ATOM x) x)
    (T
      (list 
        (atoms (list (CAR x))) 
        (atoms (list (CDR x)))
      )
    )
  )
)



However, it works adequately only in 2 cases - when an empty list or an atom is given as input. Any recursion and as a result we get Stack Overflow

Question - what am I doing wrong?
It seems, in my opinion, everything is correct.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nconc, 2019-03-12
@nconc

options:

(defun atoms (w)
  (loop for a in w
        if (atom a) collect a
        else append (atoms a)))

>  (atoms '((a b) c nil (d (e f g))))
(A B C NIL D E F G)

(defun atoms (w)
  (typecase w (atom `(,w))
            (t (mapcan #'atoms w))))

>  (atoms '((a b) c nil (d (e f g))))
(A B C NIL D E F G)

(defun atoms (w)
  (if (atom w) `(,w) (mapcan #'atoms w)))

>  (atoms '((a b) c nil (d (e f g))))
(A B C NIL D E F G)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question