(define fun4
(lambda ( ls)
(cond ((null? ls ) #f)
(cons (((eqv? 'a (car ls))) && ((eqv? 'b (cdr ls)))))
(else (pattern2 cdr ls)))))
これでエラーが表示されます - プロシージャ アプリケーション: 予想されるプロシージャ、与えられた: #t (引数なし)、私のコードのエラーは何ですか。ロジックは大丈夫ですか?
ソリューションには非常に多くのエラーがあります。それぞれの条件で何が問題なのかを見てみましょう。
#f
すぐに戻りcadr
、2 番目の要素へのアクセスに使用する方法に注意する必要があります。&&
これは、Scheme では機能しないand
ため、論理演算に使用する必要があります。また、各テストを囲む不必要で誤った括弧があります(ちなみに、これらは「予期される手順」エラーの原因となったものです)cddr
。fun4
また、再帰を進めるために呼び出す必要があります。pattern2
これは問題を解決する正しい方法です。上記の問題がどのように対処されたかに注意してください。
(define fun4
(lambda (ls)
(cond ((null? ls) #t) ; 1
((null? (cdr ls)) #f) ; 2
((not (and (eq? 'a (car ls)) (eq? 'b (cadr ls)))) #f) ; 3
(else (fun4 (cddr ls)))))) ; 4
常に手順をテストしてください。上記は正しく機能します。
(fun4 '())
=> #t
(fun4 '(a))
=> #f
(fun4 '(a b))
=> #t
(fun4 '(a b a))
=> #f
(fun4 '(a b a b))
=> #t
最後の注意として、空のリストがパターンに従っていないと想定されている場合は、呼び出す前にチェックして、最初の入力リストが空であるかどうかfun4
を返します。#f
非常に多くの車輪の再発明。SRFI 1 を使用するだけです。
(require srfi/1)
(define (fun4 lst)
(every eq? lst (circular-list 'a 'b)))
(a b a)
(これは、無効ではなく有効であるという仮定の下で動作します。)
(define fun
(lambda (ls)
(cond ((null? ls) #t)
((and (eq? (car ls) 'a) ; the first item is a
(list? (cdr ls)) ; the rest of the list
(not (null? (cdr ls))) ; which is not null
(eq? (cadr ls) 'b) ; and it starts with b
(fun (cddr ls))) #t) ; and the rest of the expression is
(else #f)))) ; also in the A B format
ランニング:
> (fun '(a b a b))
#t
> (fun '(a b a))
#f
> (fun '(a b))
#t
> (fun '(a))
#f
> (fun '())
#t
>