编辑代码

import Foundation  
  
// 定义一个枚举来表示运算符  
enum Operator: String {  
    case add = "+"  
    case subtract = "-"  
    case multiply = "*"  
    case divide = "/"  
    case power = "^"  
    case squareRoot = "sqrt"  
    case sine = "sin"  
      
    func evaluate(withLeftOperand left: Double, rightOperand: Double) -> Double {  
        switch self {  
        case .add:  
            return left + right  
        case .subtract:  
            return left - right  
        case .multiply:  
            return left * right  
        case .divide:  
            if right == 0 {  
                fatalError("Division by zero")  
            }  
            return left / right  
        case .power:  
            return pow(left, right)  
        case .squareRoot:  
            if left < 0 {  
                fatalError("Cannot take square root of a negative number")  
            }  
            return sqrt(left)  
        case .sine:  
            return sin(left)  
        }  
    }  
}  
  
// 定义操作数类型  
typealias Operand = Double  
  
// 定义运算符优先级  
enum Precedence: Int {  
    case addition = 1  
    case multiplication = 2  
    case unary = 3 // 例如负号  
}  
  
// 解析器类  
class ExpressionParser {  
    private var tokens: [String] // 分词后的表达式  
    private var index = 0 // 当前解析的token索引  
    private var operands = ArrayStack<Operand>() // 操作数栈  
    private var operators = ArrayStack<String>() // 运算符栈  
  
    // 初始化解析器  
    init(expression: String) {  
        // 分词逻辑,将表达式分割成tokens  
        self.tokens = tokenize(expression)  
    }  
      
    // 分词逻辑,这里简化处理,假设输入已经是token化的字符串数组  
    private func tokenize(_ expression: String) -> [String] {  
        // 实际的分词逻辑应该考虑空格、数字、运算符和括号等  
        // 这里简化为直接返回空格分隔的字符串数组  
        return expression.components(separatedBy: .whitespacesAndNewlines)  
    }  
      
    // 获取当前token  
    private func currentToken() -> String {  
        return tokens[index]  
    }  
      
    // 移动到下一个token  
    private func advance() {  
        index += 1  
    }  
      
    // 检查当前token是否是特定字符  
    private func peekIs(character: Character) -> Bool {  
        return currentToken().first == character  
    }  
      
    // 检查当前token并移动到下一个token  
    private func consumeIs(character: Character) -> Bool {  
        if peekIs(character: character) {  
            advance()  
            return true  
        }  
        return false  
    }  
      
    // 抛出解析错误  
    private func error(message: String) -> Never {  
        fatalError("Parse error: \(message) at index \(index)")  
    }  
      
    // 获取运算符的优先级  
    private func precedence(ofOperator operator: String) -> Precedence {  
        switch operator {  
        case "+", "-":  
            return Precedence.addition  
        case "*", "/":  
            return Precedence.multiplication  
        default:  
            return Precedence.unary  
        }  
    }  
      
    // 判断是否需要处理运算符  
    private func shouldApplyOperator(_ operator: String) -> Bool {  
        if operators.isEmpty {  
            return true  
        }  
        let topOperator = operators.peek()  
        return precedence(ofOperator: operator) <= precedence(ofOperator: topOperator)  
    }  
      
    // 处理一个运算符  
    private func applyOperator(_ operator: String) {  
        let rightOperand = operands.pop()  
        let leftOperand = operands.pop()  
        let result: Operand  
        switch operator {  
        case "+":  
            result = leftOperand + rightOperand  
        case "-":  
            result = leftOperand - rightOperand  
        case "*":  
            result = leftOperand * rightOperand  
        case "/":  
            if rightOperand == 0 {  
                error(message: "Division by zero")  
            }  
            result = leftOperand / rightOperand  
        default:  
            error(message: "Unknown operator")  
        }  
        operands.push(result)  
    }  
      
    // 解析表达式  
    func parse() -> Operand {  
        while !tokens.isEmpty {  
            if let firstCharacter = tokens[index].first {  
                switch firstCharacter {  
                case "+", "-", "*", "/":  
                    // 处理运算符  
                    while !operators.isEmpty && shouldApplyOperator(tokens[index]) {  
                        applyOperator(operators.pop())  
                    }  
                    operators.push(tokens[index])  
                    advance()  
                case "(":  
                    // 左括号直接压栈  
                    operators.push(tokens[index])  
                    advance()  
                case ")":  
                    // 右括号需要弹出栈中运算符并计算,直到遇到左括号  
                    while !operators.isEmpty && operators.peek() != "(" {  
                        applyOperator(operators.pop())  
                    }  
                    if operators.isEmpty {  
                        error(message: "Mismatched parentheses")  
                    }  
                    operators.pop// 移除左括号
                    advance()
                    case let digit where digit.isNumber:
                    // 处理数字(操作数)
                    var value = 0.0
                    while index < tokens.count, let character = tokens[index].first, character.isNumber || character == "." {
                    value = value * 10 + (character as String).doubleValue!
                    advance()
                }
                operands.push(value)
                default:
                // 未知字符,抛出错误
                error(message: "Unknown token (tokens[index])")
            }
        } else {
        // 空字符串token,抛出错误
        error(message: "Empty token")
    }
}

// 应用剩余的运算符  
    while !operators.isEmpty {  
        if operators.peek() == "(" {  
            error(message: "Mismatched parentheses")  
        }  
        applyOperator(operators.pop())  
    }  
      
    // 最终栈中应该只剩下一个操作数,即表达式的值  
    if operands.count != 1 {  
        error(message: "Invalid expression")  
    }  
      
    return operands.pop()  
}  
  
// 辅助栈类  
private class ArrayStack<T> {  
    private var elements = [T]()  
      
    func push(_ element: T) {  
        elements.append(element)  
    }  
      
    func pop() -> T {  
        if elements.isEmpty {  
            fatalError("Stack is empty")  
        }  
        return elements.removeLast()  
    }  
      
    func peek() -> T {  
        if elements.isEmpty {  
            fatalError("Stack is empty")  
        }  
        return elements.last!  
    }  
      
    func isEmpty() -> Bool {  
        return elements.isEmpty  
    }  
}
}
  
// 复数类  
class ComplexNumber {  
    var real: Double  
    var imaginary: Double  
      
    init(_ real: Double, _ imaginary: Double) {  
        self.real = real  
        self.imaginary = imaginary  
    }  
      
    // 加法  
    func +(other: ComplexNumber) -> ComplexNumber {  
        return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)  
    }  
      
    // 减法  
    func -(other: ComplexNumber) -> ComplexNumber {  
        return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)  
    }  
      
    // 乘法  
    func *(other: ComplexNumber) -> ComplexNumber {  
        let realPart = self.real * other.real - self.imaginary * other.imaginary  
        let imaginaryPart = self.real * other.imaginary + self.imaginary * other.real  
        return ComplexNumber(realPart, imaginaryPart)  
    }  
      
    // 除法  
    func /(other: ComplexNumber) -> ComplexNumber {  
        let denominator = other.real * other.real + other.imaginary * other.imaginary  
        let realPart = (self.real * other.real + self.imaginary * other.imaginary) / denominator  
        let imaginaryPart = (self.imaginary * other.real - self.real * other.imaginary) / denominator  
        return ComplexNumber(realPart, imaginaryPart)  
    }  
      
    // 正弦函数计算(仅针对实部)  
    func sin() -> Double {  
        return sin(self.real)  
    }  
      
    // 字符串表示  
    override var description: String {  
        if imaginary >= 0 {  
            return "\(real)+\(imaginary)i"  
        } else {  
            return "\(real)\(imaginary)i"  
        }  
    }  
}
  
// 无穷精度整数类  
class BigInteger {  
    var value: String  
      
    // 初始化方法  
    // ...  
      
    // 加、减、乘、除、求模等运算方法  
    // ...  
}  
  
// 计算器类  
class Calculator {  
    private let parser: ExpressionParser  
      
    init() {  
        parser = ExpressionParser()  
    }  
      
    // 计算基本数学表达式  
    func evaluate(expression: String) -> Double {  
        let ast = parser.parse(expression)  
        return parser.evaluate(ast)  
    }  
      
    // 计算复数运算  
    func evaluateComplex(expression: String) -> ComplexNumber {  
        // 解析并计算复数表达式  
        // ...  
    }  
      
    // 计算无穷精度整数运算  
    func evaluateBigInteger(expression: String) -> BigInteger {  
        // 解析并计算无穷精度整数表达式  
        // ...  
    }  
}  
  
// 使用示例  
let calculator = Calculator()  
let resultBasic = calculator.evaluate("3+5*4")  
let resultWithParentheses = calculator.evaluate("1+(3+5)*4")  
  
// 拓展功能使用示例  
let complexResult = calculator.evaluateComplex("2+3i * 4-5i")  
let bigIntegerResult = calculator.evaluateBigInteger("12345678901234567890 * 98765432109876543210")  
  
print("Basic result: \(resultBasic)")  
print("Result with parentheses: \(resultWithParentheses)")  
print("Complex result: \(complexResult)")  
print("BigInteger result: \(bigIntegerResult)")