1
#lang scheme

(define consecutive?
  (lambda(a b c)
    ((cond [(and (= (- b a) 1) (or (= (- c b) 1) (= (- a c) 1))) "true"]
           [(and (= (- a b) 1) (or (= (- c a) 1) (= (- b c) 1))) "true"]
           [(and (= (- c a) 1) (or (= (- a b) 1) (= (- b c) 1))) "true"]
           [(and (= (- a c) 1) (or (= (- c b) 1) (= (- b a) 1))) "true"]
           [else "false"]))))

(consecutive? 2 3 4)

为什么这会出错?

4

1 回答 1

5

你有一个双 (( 在 cond 之前。它应该是

(define consecutive? 
  (lambda(a b c) 
    (cond
      [(and (= (- b a) 1)(or (= (- c b) 1)(= (- a c) 1))) "true"]
      [(and (= (- a b) 1)(or (= (- c a) 1)(= (- b c) 1))) "true"]
      [(and (= (- c a) 1)(or (= (- a b) 1)(= (- b c) 1))) "true"]
      [(and (= (- a c) 1)(or (= (- c b) 1)(= (- b a) 1))) "true"]
      [else "false"])))

编辑如果我正确理解您的算法,更通用的版本将是:

(define (diff1? lst)
  (or (empty? lst)
      (empty? (cdr lst))
      (and (= 1 (- (cadr lst) (car lst)))
           (diff1? (cdr lst)))))

(define (consecutive-new? . lst)
  (diff1? (sort lst <)))

diff1在哪里?只是检查数字是连续的(n,n+1,n+2 ...)和连续新的?用排序的列表调用前者。

于 2013-10-08T13:11:55.903 回答