2013-04-30 48 views
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)))) 

當我嘗試輸入「(A B A)我得到以下錯誤:

The object (a b a) is not applicable 

誰能幫我這個錯誤?由於

回答

3

你寫

(equal? reverse-sequence(inSeq) inSeq) 

其試圖調用(inSeq)作爲參數的函數。它應該閱讀:

(equal? (reverse-sequence inSeq) inSeq) 
+0

謝謝你,那工作 – yrazlik 2013-04-30 19:25:10

2

記住,在方案來調用參數x程序f正確的做法是:(f x)。這就解釋了爲什麼這段代碼不工作:

reverse-sequence(inSeq) 

它應該是:

(reverse-sequence inSeq) 

要知道,你會遇到麻煩,如果收到的參數不是序列,你會得到一個值無效價值,你不會得到正確的答案。另外,你可以使用內置的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)))) 
+0

謝謝,我想我會很不習慣函數式編程AFER面向對象編程:) – yrazlik 2013-04-30 19:25:39

相關問題