user3281840
user3281840

Reputation: 9

Count symbols in a nested list

Function countSymbols takes a nested list of numbers and symbols as input, and returns the count of all symbols in the input list.

I had tried to get the output but couldn't do it. Can you help me with this. This is my code:

(define (countsymbols mylist)
 (if (null? mylist) mylist
      (if (symbol? (car mylist))
          (+ (countsymbols(car mylist)) (countsymbols( cdr mylist)))
          (+1 (countsymbols (cdr mylist))))))

Output should look like this:

(countSymbols '(2 56 x (1 y)))

returns 2

Upvotes: 1

Views: 853

Answers (1)

uselpa
uselpa

Reputation: 18917

You were close, but had 2 errors:

  1. the base case must return 0, not null
  2. a symbol is not a list, so you cannot recurse down on it; treat both seperately.

Like so:

(define (countsymbols mylist)
  (if (null? mylist) 
      0
      (let ((c (car mylist)))
        (cond
          ((list? c)   (+ (countsymbols c) (countsymbols (cdr mylist))))
          ((symbol? c) (+ 1 (countsymbols (cdr mylist))))
          (else        (countsymbols (cdr mylist)))))))

Upvotes: 2

Related Questions