Swift Recursive Enumerations

«  Autorelease Pool Block
Kadane's Algorithm  »

In Swift, we could use recursive enumeration to iterate instance of a enumeration to another enumeration cases. By adding indirect before it, we could simply do it, it tells the compiler to insert the necessary layer of indirection. ex:

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)
}

// Test

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)
    }
}

print(evaluate(product))
// Prints "18"

Reference

https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html

Published on 20 Mar 2020 Find me on Facebook, Twitter!

«  Autorelease Pool Block
Kadane's Algorithm  »

Comments

    Join the discussion for this article at here . Our comments is using Github Issues. All of posted comments will display at this page instantly.