In: Computer Science
Write a LISP function COUNTX which takes an atom and a list and returns the number of top-level occurrences of the atom in the list. For example: (COUNTX ‘A ‘(A (A B) B A B A (B A)) Returns the value 3, the other two A’s are not at the top level
Answer
(defun COUNTX (a lst) ;function COUNTX that takes an atom and a list
(cond
((null lst) 0) ;return 0 when list is empty
((equal a (car lst)) ;if given atom is the head of the list
(+ 1 (COUNTX a (cdr lst)))) ;add 1 to the value returned by the recursive call of COUNTX
(t (COUNTX a (cdr lst))))) ;else, call COUNTX with the rest of the given list
Output
Note - Please let me know if you have any query.