zoukankan      html  css  js  c++  java
  • Swift枚举-相关值与递归枚举

    代码:

    enum ArithmeticExpression {
        // 相关值
        case Number(Int)
        // 递归枚举
        indirect case Addition(ArithmeticExpression, ArithmeticExpression)
        indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
        indirect case Division(ArithmeticExpression, ArithmeticExpression)
    }
    
    func evaluate(expression: ArithmeticExpression) -> Int {
        switch expression {
            case .Number(let value):
                return value
            case .Addition(let left, let right):
                return evaluate(left) + evaluate(right)
            case .Multiplication(let left, let right):
                return evaluate(left) * evaluate(right)
            case .Division(let left, let right):
                return evaluate(left) / evaluate(right)
        }
    }
    
    let five = ArithmeticExpression.Number(5)
    let four = ArithmeticExpression.Number(4)
    let sum = ArithmeticExpression.Addition(five, four)
    let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
    let quotient = ArithmeticExpression.Division(five, four)
    
    print(evaluate(sum))
    print(evaluate(product))
    print(evaluate(quotient))

    输出:

    9
    18
    1
  • 相关阅读:
    LeetCode: 389 Find the Difference(easy)
    LeetCode: 669 Trim a Binary Search Tree(easy)
    C++: 内联函数
    C++: STL迭代器及迭代器失效问题
    LeetCode: 371 Sum of Two Integers(easy)
    etcdctl命令
    Etcd介绍
    docker基础镜像打包
    docker常见问题总结
    更改容器内时区
  • 原文地址:https://www.cnblogs.com/xwoder/p/4734981.html
Copyright © 2011-2022 走看看