Dr Racket中的语法错误

时间:2016-10-24 04:51:03

标签: scheme racket

窗口一直说最后一部分显示错误(...(count-even-strings (rest alist)))
说它是在额外的部分找到的,但我不知道如何解决它。

;; consumes a list of strings, list, and produces the number of strings in list that have an even length

(define (count-even-strings alist)
  (cond
    [(empty? alist) 0]
    [else (+ (cond [(even? (string-length (first alist))) true]) 1)]
[else 0]) (count-even-strings (rest alist)))

1 个答案:

答案 0 :(得分:0)

使用正确对齐代码的编辑器,如DrRacket,您可以看到您的函数具有以下结构:

(define (count-even-string1s alist)
  (cond
    [(empty? alist) 0]
    [else (+ (cond [(even? (string-length (first alist))) true])
             1)]
    [else 0])
  (count-even-strings1 (rest alist)))

并且在同一else内有两个cond,这是不正确的,而最后一部分在cond之外。

使用if的正确解决方案如下:

 (define (count-even-strings alist)
  (if (empty? alist)
      0
      (+ (if (even? (string-length (first alist)))
             1
             0)
         (count-even-strings (rest alist)))))

(count-even-strings '("a" "ab" "c""))   ;; => 2

或使用单个条件:

(define (count-even-strings alist)
  (cond ((empty? alist) 0)
        ((even? (string-length (first alist))) (+ 1 (count-even-strings (rest alist))))
        (else (count-even-strings (rest alist)))))