Я использую следующий рецепт поваренной книги для замены неуникальных подстрок в тексте:
(defn string-splice
"cookbook recipe: http://gettingclojure.wikidot.com/cookbook:strings
Given three arguments, string-splice will replace a portion of the old string at the
given offset equal to the length of the replacement. The resulting string will be the
same length as the original. The optional fourth argument
specifies the length of text to be replaced. If this argument length is greater than the
length of the new string, then the result will be shorter than the original string."
([target new offset] (string-splice target new offset (count new)))
([target new offset length]
(str (subs target 0 offset) new (subs target (+ offset length)) ) ) )
Теперь предположим, что у меня есть следующая строка с ошибкой
(def bad-st "mary had a littl lam whose fleec was whiteas snw.")
и следующий список исправлений с соответствующим индексом, указывающим, где слово с ошибкой встречается в bad-st:
(def corrections '(Mary 0 Little 11 fleck 27 white as 37 Snow 45))
Если я хочу кумулятивно подставить каждое из этих исправлений в строку, а также сместить символы в строке, чтобы учесть исправление, которое длиннее или короче, чем подстрока с ошибкой, я могу использовать версию кода сокращения, указанную для связанная проблема.
(reduce (fn [st [x y ]]
(string-splice st x y (count x) ))
bad-st
(partition 2 corrections))
Однако это не приводит к правильному сдвигу символов в исходном тексте. Выход
"Mary had a Littlelam whose fleck was white asSnow"
Может ли кто-нибудь сказать мне, что я делаю неправильно, и предложить исправление?