1

我正在尝试检测方案中的回文列表。这是我的代码:

;- Input : Takes only one parameter named inSeq
;- Output : It returns the reverse of inSeq if inSeq is a sequence.
; Otherwise it produces an error.
;- Examples :
; (reverse-sequence '(a b c)) --> evaluates to (c b a)
; (reverse-sequence '()) -------> evaluates to ()
(define reverse-sequence
 (lambda (inSeq)
   (if (sequence? inSeq)
       (if (null? inSeq) 
           inSeq 
           (append (reverse-sequence (cdr inSeq))
                   (list (car inSeq)))))))

;- Input : Takes only one parameter named inSeq
;- Output : It returns true if inSeq is a sequence and it is a palindrome.
; It returns false if inSeq is a sequence but not a plaindrome.
; Otherwise it gives an error.
;- Examples :
; (palindrome? '(a b a)) --> evaluates to true
; (palindrome? '()) -------> evaluates to true
; (palindrome? '(a 1 a)) --> produces an error
(define palindrome
 (lambda (inSeq)
   (if (sequence? inSeq) 
       (if (equal? reverse-sequence(inSeq) inSeq ) 
           #t 
           #f))))

当我尝试输入 '(aba) 我收到以下错误:

The object (a b a) is not applicable

谁能帮我解决这个错误?谢谢

4

2 回答 2

3

你写了

(equal? reverse-sequence(inSeq) inSeq )

它试图(inSeq)作为没有参数的函数调用。它应该是:

(equal? (reverse-sequence inSeq) inSeq )
于 2013-04-30T19:10:49.387 回答
2

f请记住,在 Scheme 中,在参数上调用过程的正确方法x是:(f x). 这就解释了为什么这个片段不起作用:

reverse-sequence(inSeq)

它应该是:

(reverse-sequence inSeq)

请注意,如果收到的参数不是一个序列,您将遇到麻烦,您将获得一个void值并且您不会得到正确的答案。此外,您可以使用内置reverse过程,但我想您想自己实现它 - 考虑到这一点,最好反转列表以将结果累积到参数中(尾递归),所以你不需要append结果(很贵),只cons需要结果(很便宜)。这就是我的意思:

(define (reverse-sequence inSeq)
  (if (not (sequence? inSeq))
      '()  ; can't reverse if it's not a sequence
      (let loop ((inSeq inSeq)
                 (reversed '()))
        (if (null? inSeq)
            reversed
            (loop (cdr inSeq) (cons (car inSeq) reversed))))))

(define (palindrome inSeq)
  (if (not (sequence? inSeq))
      #f
      (equal? inSeq (reverse-sequence inSeq))))
于 2013-04-30T19:16:38.863 回答