1

ネストされたリストから文字列を削除する手順を書いています。例:

(define fubar '(("a" -1 7) (2 "c") ("d") (-2)))
(remove strings fubar) should return '((-1 7) (2) () (-2)).

cdrリストはネストされているため、リストを単純に下に移動することはできないため、各リストのすべての要素を順番に個別に選択し、文字列があるかどうかを確認する方法が必要です。それを行う方法についてのアイデアはありますか?

4

2 に答える 2

2

リストのリストをトラバースするソリューションは、ソリューションのよく知られたテンプレートに従います。一般的な構造を示しますので、空欄を埋めることができます。自分でソリューションを見つけた方がはるかに優れています。意味!

(define (remove-strings lst)
  (cond (<???> <???>) ; if the list is empty, return the empty list
        ((not (pair? <???>)) ; if the current element is not a list
         (if (string? <???>) ; if the current element is a string
             (remove-strings <???>) ; simply advance recursion over cdr (*)
             (cons <???>                 ; else keep the current element
                  (remove-strings <???>)))) ; advance recursion over cdr
        (else                         ; otherwise it's a list of lists
         (cons (remove-strings <???>)     ; advance recursion over car
               (remove-strings <???>))))) ; advance recursion over cdr

(*)では、新しいリストを作成する過程で見つけたすべての文字列を単純に無視して「削除」していることに注意してください。次の行では、文字列でない場合は、出力リストを作成する間、要素を保持します。上記は、任意にネストされたリストに対して機能します。

于 2013-10-30T01:06:58.593 に答える
1

これはあなたが始めるためのスケルトンです。ツリー再帰のトリックは、車の再帰と、車自体がリストの場合の cdr です。

(define (remove-strings fubar)
 (cond ((null? fubar) ...)
       ((pair? (car fubar)) 
        (cons (... (car fubar)) (... (cdr fubar))
       (else ...)))
于 2013-10-30T00:55:59.457 に答える