Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
Select your favorite languages :
  • Or search :

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.

(def whitelist #{#'foo #'bar #'baz #'barfl})
(some-> str symbol resolve whitelist (.call))
(some-> str {"foo" foo "bar" bar "baz" baz "barfl" barfl} (.call))
IDENTIFICATION DIVISION.
PROGRAM-ID. reverse string.
PROCEDURE DIVISION.
    EVALUATE str
       WHEN foo
	  PERFORM foo
       WHEN bar
          PERFORM bar
       WHEN baz
	  PERFORM baz 
       WHEN barfl
	  PERFORM barfl
       WHEN OTHER
	  CONTINUE
    END-EVALUATE.	
STOP RUN.
switch (str)
{
    case nameof(Foo):
        Foo();
        break;
    case nameof(Bar):
        Bar();
        break;
    case nameof(Baz):
        Baz();
        break;
    case nameof(Barfl):
        Barfl();
        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()
}
case str of
  "foo" -> foo
  "bar" -> bar
  "baz" -> baz
  "barfl" -> barfl
switch (str) {
  case "foo":
    foo();
    break;
  case "bar":
    bar();
    break;
  case "baz":
    baz();
    break;
  case "barfl":
    barfl();
    break;
}
switch ($str) {
  case "foo":
    foo();
    break;
  case "bar":
    bar();
    break;
  case "baz":
    baz();
    break;
  case "barfl":
    barfl();
    break;
}
case str of
  'foo': foo;
  'bar': bar;
  'baz': baz;
  'barfl': barfl;
end;
my %proc = map { $_ => \&$_ } qw(foo bar baz barfl);
$proc{$str}->() if exists $proc{$str};
switch = {'foo': foo, 
	'bar': bar, 
	'baz': baz, 
	'barfl': barfl
	}

switch_funct = switch.get(string)
if switch_funct : switch_funct()
method(str).call if ["foo", "bar", "baz", "barfl"].include?(str)
match str {
    "foo" => foo(),
    "bar" => bar(),
    "baz" => baz(),
    "barfl" => barfl(),
    _ => {}
}
Imports Microsoft.VisualBasic
CallByName(receiver, str, CallType.Method)
Select Case str
    Case NameOf(Foo)
        Foo()
    Case NameOf(Bar)
        Bar()
    Case NameOf(Baz)
        Baz()
    Case NameOf(Barfl)
        Barfl()
End Select

New implementation...
tkoenig