scheme - Count atoms in a list structure -


i need find how many elements given input has. input can list or symbol, example:

  • 'a => 1 element
  • '(3 . 4) => 2 elements
  • '(a b . c) => 3 elements
  • '((a b . c) 3 . 4) => 5 elements

one problem when i'm going through input, every element can list of own, or pair (just started learning scheme, tools right car/cdr), so, when should stop loop? when if (null? x) condition true? or maybe when if (null? (car x)) true?

the title of question should changes how count atoms in list structure. there numerous questions on se it. here how:

  1. if element pair, result sum of car , cdr applied same procedure.
  2. else length 1

edit

here's above algorithm code:

(define (count-all-atoms x)   (if (pair? x)       (+ (count-all-atoms (car x))          (count-all-atoms (cdr x)))       1)) 

to comment comments i've got there 2 more ways implement , of them give correct answer op's examples. has how interpret () be.

depending on '(()) should counted 0, 1 or 2 elements. 0 since it's lists without atoms, 1 since 1 list 1 null element (not counting null terminator) or 2 since it's same dotted pair 2 null elements ((() ())). it's last 1 text described, here 2 other ways:

;; count (()) , () 0 ;; no nil value counted list without elements (define (count-non-nil-atoms x)   (if (pair? x)        (+ (count-non-nil-atoms (car x))           (count-non-nil-atoms (cdr x)))       (if (null? x)           0            1)))  ;; count (()) 1 , () 0 ;; ie. count nil atom in car position not list terminator ;; common (define (count-atoms x)   (if (pair? x)       (let ((a (car x)) (d (cdr x)))                 (+  (if (null? a) 1 (count-atoms a))             (count-atoms d)))       (if (null? x) 0 1))) 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -