1

したがって、関数はすべて文字列である3つの引数を取る必要があります。1つ目は元の文字列です。2つ目は、文字列内のどの文字を変更する必要があるかです。3番目は文字を変更する必要があるものです。例えば、

~ (switch-up "aabcc" "abc" "def")

「ddeff」

これからどうやって始めたらいいのかわからない。何か助けはありますか?

4

2 に答える 2

0

これは宿題のように見えるので、利用可能な手順を使用して問題を解決するためのヒントをいくつか示します。問題をより単純な部分に分割することから始めます。最初に、switch-up基本的に入力文字列の各文字を繰り返し処理し、各文字を順番に処理して、結果を使用して新しい文字列を作成する実際の手順です。ヒント:文字列の最初の文字と残りの文字を取得するためにstring-refとを使用します。これをsubstring文字列のとと考えてください。carcdr

(define (switch-up lst letters replacements)
  (if <???>                                      ; if the string is empty
      <???>                                      ; return the empty string ""
      (string-append (replace <???> <???> <???>) ; otherwise string-append the replacement of the first character in the string
                     (switch-up <???> letters replacements)))) ; and advance the recursion over the rest of the string

次に、replace単一の文字と文字および置換を指定して、置換された文字列、または見つからなかった場合は同じ入力文字を持つ文字列を返すプロシージャが必要です。

(define (replace c ls rs)
  (let ((idx (index-of ls c)))       ; get the index of c in the `ls` string
    (if idx                          ; if the index was found
        (string (string-ref rs idx)) ; then get the corresponding value from `rs`
        (string c))))                ; otherwise, return c unchanged

そして最後に、前の手順で文字列内の文字のインデックスを返すヘルパー手順を定義するのに役立つことがわかりましたls(または#f文字が文字列に見つからなかった場合)ので、置換文字列で簡単に見つけることができます。strヒント:を使用して文字のリストに変換すると非常に便利ですstring->list

(define (index-of str c)
  <???>) ; ToDo: return the 0-based index of c inside str

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

(switch-up "aabcc" "abc" "def")
=> "ddeff"

代替方法:string->list最初に文字列を文字のリストに変換し(を使用)、最後にを使用して文字列を文字列に戻すと、問題の解決が簡単になる場合がありますlist->string

于 2013-03-18T22:42:32.507 に答える
0

概要:古い文字から新しい文字へのマッピングを作成します。元のリストをたどり、古い文字を新しい文字に置き換えます。すべての引数がリストであると仮定します(そうでない場合は必要ですstring->list):

(define (switch-up list old new)
  (let ((old-to-new (map cons old new)))
    (let switching ((list list) (result '())
      (if (null? list)
          (reverse result)
          (switching (cdr list)
                     (cons (cond ((assoc (car list) old-to-new) => cdr)
                                 (else (car list)))
                           result))))))
于 2013-03-18T22:38:56.380 に答える