Recursively check for atoms in a list

I am trying to write a small recursive program that checks a list and returns t if each element is an atom. The problem is that when a function receives an empty list, it returns t instead of the desired result nil . I cannot find a way to return nil for an initially empty list and still work correctly in a recursive manner.

(defun only-atoms (in)
  (if (null in)
    t
    (and (atom (first in)) (only-atoms (cdr in)) )
  )
)
+5
source share
5 answers

A function can be implemented without recursion using, for example every, as in:

(defun only-atoms (list)
  (and list (every #'atom list)))

, T NIL :

  • T, (null in) , . NIL. if and.

  • , . (rest in). , , .

  • only-atoms, , .

:

    (defun only-atoms (list)
      (and list
          (atom (first list))
          (or (null (rest list))
              (only-atoms (rest list)))))
+2

COND, :

  • → nil
  • → ?; : LENGTH
  • else → ?
+1

, ! , , .

" - " (every #'atom list). and.

, SICP-, :

(defun not-empty-and-all-atoms (list)
  (and list
       (all-atoms list)))

(defun all-atoms (list)
  (if (endp list)
      t
      (and (atom (first list))
           (all-atoms (rest list)))))
+1

:

(defun lat-p (lst)
           (labels ((lat-p* (lst) 
                      (cond
                       ((null lst) t)
                       ((atom (car lst)) (lat-p* (cdr lst)))
                       (t nil))))
             (if lst
                 (lat-p* lst)
                 nil)))

( ) :

(defun lat-p (lst)
           (and lst (every #'atom lst)))
0

You can split your function into two parts and provide an initial screenshot nilbefore entering recursion. The following code is one way to do this (I tried to bring it as close as possible to the provided code):

(defun only-atoms (in)
  (defun only-atoms-iter (in)
    (if (null in)
        t
      (and (atom (first in)) (only-atoms-iter (cdr in)))))

  (unless (null in)
      (only-atoms-iter in)))

This is also a good opportunity to make your function tail recursive:

(defun only-atoms (in)
  (defun only-atoms-iter (in state)
    (if (null in)
        state
      (only-atoms-iter (cdr in) (and state (atom (first in))))))

  (unless (null in)
      (only-atoms-iter in t)))
-1
source

All Articles