|
|
|
|
|
by Cyther606
4186 days ago
|
|
As another illustrative example, let's say we want to create a library for working with mathematical expressions such as x^2 + 5*x. It's natural to define our data types like this: type
FormulaKind = enum
fkVar, ## element is a variable like 'X'
fkLit, ## element is a literal like 0.1
fkAdd, ## element is an addition operation
fkMul, ## element is a multiplication operation
fkExp ## element is an exponentiation operation
type
Formula = ref object
case kind: FormulaKind
of fkVar: name: string
of fkLit: value: float
of fkAdd, fkMul, fkExp: left, right: Formula
Nim's enum [1] is an old-school typesafe enum, as in Ada, without any fields. To avoid name clashes, it's common to prefix the enum values with a two-letter abbreviation. The case part in the object declaration introduces a checked union. So the access of f.name will raise an exception if f.kind != fkVar.[1] http://goran.krampe.se/2014/10/20/i-missed-nim/ |
|