Programming-Idioms

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

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

case str of
  'foo': foo;
  'bar': bar;
  'baz': baz;
  'barfl': barfl;
end;
(some-> str {"foo" foo "bar" bar "baz" baz} (.call))
(def whitelist #{#'foo #'bar #'baz})
(some-> str symbol resolve whitelist (.call))
switch (str) 
{
  case "foo":
    foo();
    break;
  case "bar":
    bar();
    break;
  case "baz":
    baz();
    break;
  case "barf1":
    barf1();
    break;
}
  select case (str)
  case ("foo")
     call foo
  case ("bar")
     call bar
  case ("baz")
     call baz
  case ("barfl")
     call barfl
  end select
switch str {
case "foo":
	foo()
case "bar":
	bar()
case "baz":
	baz()
case "barfl":
	barfl()
}
switch (str) {
  case "foo":
    foo();
    break;
  case "bar":
    bar();
    break;
  case "baz":
    baz();
    break;
  case "barfl":
    barfl();
    break;
}
my %proc = map { $_ => \&$_ } qw(foo bar baz barfl);
$proc{$str}->() if exists $proc{$str};
switch = {'foo': foo, 
	'bar': bar, 
	'baz': baz, 
	'barf1': barf1
	}

switch_funct = switch.get(string)
if switch_funct : switch_funct()
method(str).call if ["foo", "bar", "baz", "barfl"].include?(str)
method(str).call if ["foo", "bar", "baz", "barfl"].include?(str)
match str_ {
    "foo" => foo(),
    "bar" => bar(),
    "baz" => baz(),
    "barfl" => barfl(),
    _ => {}
}
CallByName(Me, str, CallType.Method)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

tkoenig