2012-11-14 32 views
1

所以在這裏我有幾個定義的列表中,我想用:方案功能看到的是兩端匹配

(DEFINE list0 (LIST 'j 'k 'l 'm 'n 'o 'j)) 
(DEFINE list1 (LIST 'a 'b 'c 'd 'e 'f 'g)) 
(DEFINE list2 (LIST 's 't 'u 'v 'w 'x 'y 'z)) 
(DEFINE list3 (LIST 'j 'k 'l 'm 'l 'k 'j)) 
(DEFINE list4 (LIST 'n 'o 'p 'q 'q 'p 'o 'n)) 
(DEFINE list5 '((a b) c (d e d) c (a b))) 
(DEFINE list6 '((h i) (j k) l (m n))) 
(DEFINE list7 (f (a b) c (d e d) (b a) f)) 

我想要做的是一個「endsmatch」創建一個遞歸函數功能會做這樣:

ENDSMATCH: (endsmatch 1st)應返回#t如果在列表中的第一個元素是一樣的,在列表中的最後一個元素,並返回 #f否則。也就是說,

(endsmatch '(s t u v w x y z)) 會/應返回: #f

(endsmatch (LIST 'j 'k 'l 'm 'n 'o 'j) 

會/應返回: #t

兩個(endsmatch '())(endsmatch '(a)) 應該返回#t等。

也就是功能可以讀取複雜的列表,如: (endsmatch '((a b) c (d e d) c (a b))) 然後將返回: #t 和:

(endsmatch '((a b) c (d e d) c (b a))) 

(endsmatch '((y z) y)) 

都應該返回#f

怎麼可能這個功能,因爲我被編碼對計劃很陌生,並會看到它的樣子,提前謝謝。

回答

2

試試這個,它是那樣簡單,因爲它得到:

(define (endsmatch lst) 
    (if (null? lst) 
     #t 
     (equal? (first lst) (last lst)))) 

如果您Scheme解釋不包括程序firstlast,他們是非常簡單的實現:

(define (first lst) 
    (car lst)) 

(define (last lst) 
    (cond ((null? lst) #f) 
     ((null? (cdr lst)) (car lst)) 
     (else (last (cdr lst))))) 
+0

謝謝,我要試一試。 – user1786512

+0

不適用於空列表 – finnw

+0

@finnw您是對的。我更新了我的答案,謝謝。 –

1

我已經提出了這個解決方案,但是它對於你描述的最後2個測試失敗了:

(define (endsmatch lst) 
    (let loop ((lst lst) (first '()) (last '())) 
    (cond 
     ((null? lst)   (eq? first last)) 
     ((pair? (car lst)) (loop (car lst) first last) 
          (loop (cdr lst) first last)) 
     ((null? first)  (loop (cdr lst) (car lst) (car lst))) 
     (else    (loop (cdr lst) first (car lst)))))) 


; racket test code 
(require rackunit) 
(check-eq? (endsmatch '(s t u v w x y z)) #f) 
(check-eq? (endsmatch (list 'j 'k 'l 'm 'n 'o 'j)) #t) 
(check-eq? (endsmatch '()) #t) 
(check-eq? (endsmatch '(a)) #t) 
(check-eq? (endsmatch '((a b) c (d e d) c (b a))) #t) 
; these fail 
(check-eq? (endsmatch '((a b) c (d e d) c (b a))) #f) 
(check-eq? (endsmatch '((y z) y)) #f) 

確實你說的這兩個

"(endsmatch '((a b) c (d e d) c (b a))) which would then return: #t" 

"(endsmatch '((a b) c (d e d) c (b a))) should return #f" 

這是矛盾的。

+0

對不起,我意外地創建了一個錯字,我糾正了它,如果你想重新檢查它,看看我其實是什麼意思。 – user1786512