计算列表中的符号

时间:2015-10-22 03:27:20

标签: function scheme racket

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

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

1 个答案:

答案 0 :(得分:1)

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

(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