Not too hard, the main point is that you need some kind of buffer (called prev
in my case) to wait for a possible multiplication:
(define (atomic_count lst)
(let loop ((lst lst) (prev 0))
(if (null? lst)
prev
(let ((elt (car lst)))
(cond
((list? elt) (+ prev (loop (cdr lst) (loop elt 0))))
((number? elt) (loop (cdr lst) (* prev elt)))
(else (+ prev (loop (cdr lst) 1))))))))
Testing:
> (atomic_count '(c o 2 (h 2 o) 3 o 2))
14
> (atomic_count '(h 2 o))
3
> (atomic_count '(c o 2 o 2))
5
3
solved Write scheme LISP Atomic_Count [closed]