Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Basics and Types

Enums and Subranges

Define Nim enums, iterate over them, give them string values, use pure enums, restrict values with range types, and store flags with bit sets, with C stand-ins.

Sometimes a value can only be one of a small, fixed list: a day of the week, a traffic-light color, a file mode. Nim models these with enumerations. Related to them are subrange types, which restrict a number or ordinal to a window, and sets, which hold any combination of an enum's values in a single machine word.

The Nim snippets are read-only (no Nim compiler on this site). Runnable C stand-ins are given for the underlying ideas.

Defining an enum

NIM
type
  Color = enum
    red, green, blue

var c = green
echo c              # green
echo ord(c)         # 1

Each name gets an ordinal number starting at 0. echo shows the name, not the number, because $ on an enum returns its identifier. Enums are ordinal types, so they support these operations:

NIM
echo succ(red)        # green  (next)
echo pred(blue)       # green  (previous)
echo low(Color)       # red
echo high(Color)      # blue
echo red < blue       # true

succ(blue) or pred(red) raises an error, because there is nothing before the first or after the last value.

Looping over every value

NIM
for color in Color:
  echo color, " = ", ord(color)

You can iterate over the enum type itself, or over a slice such as red .. green.

Explicit numbers and strings

NIM
type
  HttpCode = enum
    ok = 200
    notFound = 404
    serverError = 500

  Level = enum
    debug = "DEBUG"
    info  = "INFO"
    warn  = "WARN"

echo ok.ord          # 200
echo info            # INFO

Numbers must be in ascending order (gaps are allowed, but such an enum has "holes", which limits operations like succ, array indexing and iteration, so use plain consecutive enums where you can). A string value is what $ returns, which is handy for logging and serialization; the first name is still how you write it in code.

Pure enums

By default enum members live in the surrounding scope, which can clash with other names. Mark an enum {.pure.} to force the qualified form:

NIM
type
  Direction {.pure.} = enum
    north, south, east, west

let d = Direction.north

Most new code uses {.pure.} for enums with common names like none or error.

case with enums

case over an enum must cover every value (or have an else), so adding a new value makes the compiler point out every place that needs updating:

NIM
func describe(c: Color): string =
  case c
  of red: "warm"
  of green, blue: "cool"

Subrange types

A subrange restricts an ordinal type to a closed range:

NIM
type
  Age = range[0 .. 150]
  Percent = range[0 .. 100]

var a: Age = 30
a = 200          # run time: RangeDefect (compile time if a literal)

The check happens on assignment in builds with checks enabled. Subranges are cheap documentation and a tiny validation layer. They also work on enums, as in range[red .. green], and as array index types:

NIM
var counts: array[Color, int]      # one slot per Color
counts[green] += 1

Sets of enums

Nim has a built-in set type for ordinal types with a small range. A set of an enum is stored as a bitmask, so it is very fast:

NIM
type
  Permission {.pure.} = enum
    read, write, execute

var perms: set[Permission] = {Permission.read, Permission.write}
perms.incl Permission.execute        # add
perms.excl Permission.write          # remove
echo Permission.read in perms        # true
echo perms                           # {read, execute}

Set operators include + (union), * (intersection), - (difference) and <= (subset). This replaces the "bit flags" pattern from C with something type safe. Sets also work with characters and small integers, as in {'a'..'z'}.

Stand-in: an enum with names and a range check

C enums are plain integers, so this stand-in adds a name table (like Nim's $) and a checked setter (like a subrange).

C Stand-in: enum names and a subrange check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a set as a bitmask

This is what set[Permission] does under the hood.

C Stand-in: set[Permission] as bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The value 5 is binary 101: read and execute are set, write is cleared.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does echo green print for type Color = enum red, green, blue?

    $ on an enum returns its name. Use ord(green) to get the number 1.
  2. 2. What happens when a value outside a range type's bounds is assigned in a checked build?

    Subrange types are checked on assignment, so Age = range[0..150] rejects 200.
  3. 3. What does the {.pure.} pragma on an enum do?

    Pure enums avoid name clashes by forcing qualified access.
  4. 4. How is set[Permission] typically stored?

    Sets over small ordinal types are bit sets, so membership tests are a single mask operation.

Summary

  • Enums are ordinal types; $ gives names, ord the number, and succ, pred, low, high work.
  • Enum members can have explicit numbers or string values; {.pure.} forces qualified names.
  • case over an enum must be exhaustive.
  • range[a .. b] restricts values and is checked at run time; arrays can be indexed by an enum.
  • set[Enum] is a fast bit set with incl, excl, in, +, *, -.

Next: if, case and when