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

私はスキームに不慣れで、それがどのように見えるかを見るので、この関数はどのようにコーディングできますか、よろしくお願いします。

4

2 に答える 2

2

これを試してみてください、それはそれが得るのと同じくらい簡単です:

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

firstスキームインタープリターにプロシージャとが含まれていない場合last、それらの実装は非常に簡単です。

(define (first lst)
  (car lst))

(define (last lst)
  (cond ((null? lst) #f)
        ((null? (cdr lst)) (car lst))
        (else (last (cdr lst)))))
于 2012-11-14T22:09:10.360 に答える
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"

これは矛盾しています。

于 2012-11-14T22:19:25.527 に答える