03. Recursive Enumeration

It will take about 3 minutes to finish reading this article.

Enumerations and cases can be marked as indirect, which means that their associated values are stored indirectly, which allows us to define recursive data structures.
Example Code

1
2
3
4
5
6
7
8
9
10
11
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// or
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}

Call as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))

func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right) // (5 + 4) * 2
}
}
print(evaluate(product))

// “18”