Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #254 Replace value in list

Replace all exact occurrences of "foo" with "bar" in the string list x

(replace {"foo" "bar"} x)
for (var i = 0; i < x.length; i++) {
  if (x[i] == 'foo') x[i] = 'bar';
}
x = x.map((e) => e == 'foo' ? 'bar' : e).toList();
[case Elem of "foo" -> "bar"; _ -> Elem end || Elem <- X].
  where (x == "foo")
     x = "bar"
  endwhere
for i, v := range x {
	if v == "foo" {
		x[i] = "bar"
	}
}
func replaceAll[T comparable](s []T, old, new T) {
	for i, v := range s {
		if v == old {
			s[i] = new
		}
	}
}

replaceAll(x, "foo", "bar")
replaced = map (\e -> if e == "foo" then "bar" else e) x
x = x.map(e => e === 'foo' ? 'bar' : e);
import java.util.stream.Collectors;
x = x.stream()
     .map(s -> s.equals("foo") ? "bar" : s)
     .collect(Collectors.toList());
uses classes;
for i := 0 to x.count - 1 do
  if x[i] = 'foo' then
    x[i] := 'bar';
map { s/^foo$/bar/g } @x;
x = ["bar" if v=="foo" else v for v in x]
for i, v in enumerate(x):
  if v == "foo":
    x[i] = "bar"
x.map!{|el| el == "foo" ? "bar" : el}
for v in &mut x {
    if *v == "foo" {
        *v = "bar";
    }
}

New implementation...