この種の問題の解決策には、再帰を使用して途中でリストを作成する必要があるという繰り返しパターンがあります。一般的な手順を説明しましょう。空欄に記入してみましょう。
(define (createlist start end)
(if (= <???> <???>) ; the problem is solved when start and end are the same
'() ; lists end in null
(cons <???> ; if we are not done yet, we `cons` the current value of start
(createlist <???> end)))) ; with the result of calling the recursion
; notice that start is one step closer to the end, so we increment it
アルゴリズムの考え方は、各ステップで、でstart
作成されているリストに現在の値を追加し、に達するまでcons
増分し、この時点で再帰が終了することです。start
end
TheLittleSchemerまたはHowtoDesign Programsのいずれかを参照する必要があります。どちらの本も、この種の再帰的な問題の解決策をリスト上で構成する方法を説明しています。
アップデート:
これまでに作成したコードを投稿したので、正しい答えをお見せします。括弧[部分if
の後に続く括弧else
]と空白[if(
は同じではありません]には十分注意してくださいif (
。これらはSchemeでは非常に重要です。また、コードを正しくインデントすると、多くのバグを見つけるのに役立ちます。
(define (createlist start end)
(if (= start end)
'()
(cons start
(createlist (+ 1 start) end))))
<???>
これで、 getがどのように正しく入力されるかを確認できます。