我正在尝试检测方案中的回文列表。这是我的代码:
;- 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))))
当我尝试输入'(a b a)时,我收到以下错误:
The object (a b a) is not applicable
任何人都可以帮我解决这个错误吗?感谢
答案 0 :(得分:3)
你写了
(equal? reverse-sequence(inSeq) inSeq )
尝试将(inSeq)
作为无参数的函数调用。它应该是:
(equal? (reverse-sequence inSeq) inSeq )
答案 1 :(得分:2)
请记住,在Scheme中,在参数f
上调用过程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))))