0

私はスキームが初めてです。新しいリストに最初と最後の要素が含まれないように、リストを切り捨てようとしています。

前もって感謝します。

4

2 に答える 2

2

これを行うには多くの方法があります。1 つの可能性はdrop-right、最後の要素を削除するために使用し、 rest(またはcdr) を使用して最初の要素を削除することです。

(define lst '(1 2 3 4 5))
(rest (drop-right lst 1))
=> '(2 3 4)

インタープリターで が利用できない場合drop-rightは、入力リストの最後の要素を除くすべての要素を含む新しいリストを返すプロシージャを実装するだけです。1 つの手順で両方の要素の削除を組み合わせることもできます。リストに少なくとも 2 つの要素があると仮定して (そうでない場合はエラーが発生します)、空白を埋めます。

(define (truncate-first-last lst)
  (define (drop-last lst)          ; helper procedure for removing last element
    (if <???>                      ; if the rest of the list is empty
        <???>                      ; then return the empty list
        (cons <???>                ; else `cons` the first element
              (drop-last <???>)))) ; and advance the recursion
  (drop-last <???>))               ; call helper, remove first element from list

それをテストすることを忘れないでください:

(truncate-first-last '(1 2 3 4 5))
=> '(2 3 4)
于 2013-04-14T00:09:34.153 に答える