リストを受け取り、リストの要素に基づいて適切な関数を適用する単純な再帰関数を作成しようとしています。入力時:
Input: (myfunct '(plus ( minus(5 4) 3 ) )
Output: 4
そのため、文字列が何であるかを確認し、それに応じて式を再帰的に解決します。
これは私が今持っているものです(プラスだけ):
(define (myfunct lis)
((integer? (car lis)) (car lis))
((equal? 'plus (car lis)) (+ myfunct(car (cdr(lis)) myfunct(cdr(cdr lis)))))
)
//if its an integer, return it
//if its plus, call myfunct with the 2 next heads of the list
これにより、エラーが発生します (入力 "(myfunct '(plus 4 5))":
application: not a procedure;
expected a procedure that can be applied to arguments
given: #f
arguments...:
plus
エラーの理由を特定できません。説明/修正をお願いできますか?
編集:
(define (myfunct lis)
(cond ((integer? lis) lis)
((integer? (car lis)) (car lis))
((equal? 'plus (car lis))
(+ (myfunct (car (cdr lis))) (myfunct (cdr (cdr lis)))))))
で動作します:(myfunct '(plus (plus 4 5) 6)
ただし、それでも動作しません... (myfunct '(plus (plus 4 5) (plus 2 3)))
. 2 番目の引数は、void "()" として返され続けます。再帰ツリーを描画しましたが、そのエラーの理由がわかりません。何か案は?
EDIT 2: 最終的な有効な回答。なぜこれが機能し、他の機能が機能しないのか 100% 確実ではありません。その上の車は間違った値を返します。
(define (myfunct lis)
(cond ((integer? lis) lis)
;;((integer? (car lis)) (car lis))
((equal? 'plus (car lis))
(+ (myfunct (car (cdr lis))) (myfunct (cdr (cdr lis)))))
(else (myfunct (car lis)))))