Logo

Programming-Idioms

Given the enumerated type T, create a function TryStrToEnum that takes a string s as input and converts it into an enum value of type T.

Explain whether the conversion is case sensitive or not.
Explain what happens if the conversion fails.
Implementation
Ada

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Ada implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
function TryEnumToStr(const s: string; out enum: T): Boolean;
var
  code: integer;
begin
  Val(s, enum, code);
  Result := (code = 0);
end;
t = T[s]
T.values.byName(s);
T x = T.valueOf(s);
def try_str_to_enum(t, string), do: t[string]
my %T = ( RED => 1, GREEN => 2, BLUE => 3 );

sub TryStrToEnum { my $s = shift; $T{uc $s} }

print GREEN;  # prints 2
print TryStrToEnum('BLUE');  prints 3

use feature 'say';
use constant { RED => 1, GREEN => 2, BLUE => 3 };

sub TryStrToEnum { eval uc shift }

say GREEN; # prints 2
say TryStrToEnum('BLUE'); # prints 3