计算嵌套列表中的符号

时间:2014-02-26 06:29:07

标签: scheme

函数countSymbols将数字和符号的嵌套列表作为输入,并返回输入列表中所有符号的计数。

我曾试图获得输出但却无法做到。你能帮帮我吗?这是我的代码:

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

输出应如下所示:

  

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

返回2

1 个答案:

答案 0 :(得分:2)

你很亲密,但有2个错误:

  1. 基本案例必须返回0,而不是null
  2. 符号不是列表,因此您无法对其进行递归;分开对待。
  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)))))))