Paste: stringtoenum

Author: blei
Mode: text
Date: Wed, 25 Apr 2012 18:36:56
Plain Text |
import printer.(println);

[T when Enum?(T)]
stringToEnum(#T, s) {
    ..for (i in staticIntegers(EnumMemberCount(T))) {
        if (s == EnumMemberName(T, i)) {
            return Maybe(intToEnum(T, i));
        }
    }
    return nothing(T);
}

enum FooEnum (FOO, BAR, BAZ);

main() {
    println(stringToEnum(FooEnum, "FOO"));
    println(stringToEnum(FooEnum, "BAZ"));
    println(stringToEnum(FooEnum, "garbl"));
}

Annotation: fixed

Author: blei
Mode: text
Date: Wed, 25 Apr 2012 18:43:52
Plain Text |
import printer.(println);

[T when Enum?(T)]
stringToEnum(#T, s) {
    ..for (i in staticIntegers(#EnumMemberCount(T))) {
        if (s == EnumMemberName(T, i)) {
            return Maybe(intToEnum(T, Int32(unwrapStatic(i))));
        }
    }
    return nothing(T);
}

enum FooEnum (FOO, BAR, BAZ);

main() {
    println(stringToEnum(FooEnum, "FOO"));
    println(stringToEnum(FooEnum, "BAZ"));
    println(stringToEnum(FooEnum, "garbl"));
}

New Annotation

Summary:
Author:
Mode:
Body: