この関数の書き方がわからないようです。私が書き込もうとしているのは、フォームのパラメーターとしてexpand
リストを受け取り、次のように評価される関数です。lst
'(a (2 b) (3 c))
'(a b b c c c)
2 に答える
3
これは宿題のように見えるので、率直な答えはしません。代わりに、正しい方向へのいくつかの指針を示します。最も役立つヒントは、問題を 2 つの手順に分割することです。1 つは「外側」のリストを処理するためのもので、もう 1 つは内側のサブリストでエンコードされた繰り返しを生成するためのものです。
両方のプロシージャが相互に再帰的であることに注意してください (たとえば、相互に呼び出します)。手順はexpand
リストを繰り返しますが、repeat
手順は繰り返し回数を繰り返します。これは、提案されたソリューションの一般的な構造であり、空白を埋めます。
; input: lst - list to be processed
; output: list in the format requested
(define (expand lst)
(cond ((null? lst) ; if the list is null
'()) ; then return null
((not (pair? (car lst))) ; if the first element of the list is an atom
(cons <???> <???>)) ; cons the atom and advance the recursion
(else ; if the first element of the list is a list
<???>))) ; call `repeat` with the right params
; input: n - number of repetitions for the first element in the list
; lst - list, its first element is of the form (number atom)
; output: n repetitions of the atom in the first element of lst
(define (repeat n lst)
(if (zero? n) ; if the number of repetitions is zero
(expand (cdr lst)) ; continue with expand's recursion
(cons <???> ; else cons the atom in the first element and
<???>))) ; advance the recursion with one less repetition
于 2012-10-03T23:25:53.053 に答える