Back to Over

Iterators · Over · Practice Question

Search and Replace Multiple Substrings

Sign in to track your progress

Question

Given:

word:"blueberry"

Replace the text "berry" with "apple" and replace the text "blue" with "green".

Expected result:

"greenapple"

Solution

ssr/[word;("blue";"berry");("green";"apple")]

Alternative Solution

ssr[ssr[word;"blue";"green"];"berry";"apple"]

Explanation

ssr[x;y;z] replaces substring y with z in string x. Given a list of old substrings and a matching list of new ones, ssr/ uses the over iterator (/) to thread the string through each replacement in turn — the output of replacing "blue" feeds straight into the next call, which replaces "berry":

ssr["blueberry";"blue";"green"]    / "greenberry"
ssr["greenberry";"berry";"apple"]  / "greenapple"

This is the same accumulate pattern as +/ for running totals, just with ssr instead of + and strings instead of numbers — over only returns the final string after all replacement pairs have been applied.

The alternative writes the same two ssr calls out explicitly, nested inside one another, which is exactly what ssr/ is doing under the hood.