计算列表中的符号

Count symbols in a list

我如何创建一个函数 countSymbols,它将嵌套的数字和符号列表作为输入,returns 输入列表中所有符号的计数。

(countSymbols '(a)) returns 1
(countSymbols '(2 56 x (1 y))) returns 2
(countSymbols '(((a)) -2 (2 (ab b) (-1 0 1))))) returns 3

这是我试过的

(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)))))))

这个问题可以使用遍历列表列表的标准模板来解决,你应该已经在 class 中学习过了。我不会破坏编写您自己的解决方案的乐趣,而是会给您一些提示 - 填空:

(define (countSymbols lst)
  (cond ((null? lst) <???>) ; how many symbols in an empty list?
        ((not (pair? lst))  ; if this is a single elment of the list
         (if (symbol? lst)  ; check if it's a symbol, if so
             <???>          ; then we add one to the count
             <???>))        ; otherwise we add nothing
        (else               ; else we advance the recursion and add the
         (+ (countSymbols <???>)     ; result of both the `car` part
            (countSymbols <???>))))) ; and the `cdr` part of the list

它按预期工作:

(countSymbols '(a))
=> 1
(countSymbols '(2 56 x (1 y)))
=> 2
(countSymbols '(((a)) -2 (2 (ab b) (-1 0 1))))
=> 3