Skip to content
C272 edited this page Dec 18, 2019 · 4 revisions

Creating Enums

In Algo, enums are sets of values which correspond to integer values. Here's how you create an enum in Algo:

let myEnum = enum 
{
    value1,
    value2
}

Once you've defined an enum, you can access the values to return and modify by using the usual object access. For this example, it would be myEnum.value1 for the value1 field.

A good example use case for enums is to define types of fruit for a fruit shop function. Sure, you could write out the string "apple" as an argument, and compare two strings, but that would be slow, and what if you type the wrong input? With enums, there are a guaranteed limited amount of options, and they are fast to compare.

Here's that fruit shop example without enums:

let getFruit(fruit) =
{
    if (fruit == "apple") { return "apple get"; }
    if (fruit == "orange") { return "orange get"; }
}

getFruit("apple");

And here's the example using enums:

let fruits = enum
{
    apple,
    orange
}

let getFruit(fruit) = 
{
    if (fruit == fruits.apple) { return "apple get"; }
    if (fruit == fruits.orange) { return "orange get"; }
}

getFruit(fruits.apple);

They remove ambiguity, which is quite useful.

Enums as Objects

In Algo, enums are internally represented as objects which have variables with the given names (eg. value1 and value2), and a value of integers ascending from zero. So, if you define an enum as above, it's the same as doing:

let myEnum = object {
    let value1 = 0; //DON'T MUTATE THESE!
    let value2 = 1;
};

This does also mean that enums are mutable, and can be changed at runtime. This is highly recommended against, as it usually leads to unreliability and lots of spaghetti.