2014-09-27 79 views
0

我想用動態運算符創建動態算術表達式。是否可以使用動態運算符創建動態算術表達式?

我很新的快捷,下面是完整的假,但我在想沿着線的東西:

類似
class Expr { 
    var operandA:Double = 0; 
    var operandB:Double = 0; 
    var arithmeticOperator:operator = +; // total bogus 

    init(a operandA:Double, b operandB:Double, o arithmeticOperator:operator) { 
    self.operandA = operandA; 
    self.operandB = operandB; 
    self.arithmeticOperator = arithmeticOperator; 
    } 

    func calculate() -> Double { 
    return self.operandA self.arithmeticOperator self.operandB; // evaluate the expression, somehow 
    } 
} 

var expr = Expr(a: 2, b: 5, o: *); 
expr.calculate(); // 10 

將事情是可能的,以某種方式(不定義操作功能/方法,那是)?

+0

接受類型的拉姆達'(雙人間,雙人間) - >雙'。然後稍後調用它,例如'arithmeticOperator(operandA,operandB)'。有關此技術的簡要概述,請參見[Swift語言中的函數式編程](https://medium.com/swift-programming/2-functional-swift-c98be9533183)。然後這個函數可以在其他地方定義,並用作'Expr(2,5,Operators.MUL)'。 – user2864740 2014-09-27 00:28:45

+0

@ user2864740我明白你的意思了,是的。也許我應該走這條路。我實際上是在試圖避免創建函數(不確定爲什麼;可能是懶惰:)),但我可以給這個鏡頭。 – Codifier 2014-09-27 00:43:14

回答

2

最接近的,我可以說是使用自定義字符爲運營商提供,然後使用開關情況來計算表達式,

protocol Arithmetic{ 
    func + (a: Self, b: Self) -> Self 
    func - (a:Self, b: Self) -> Self 
    func * (a:Self, b: Self) -> Self 
} 

extension Int: Arithmetic {} 
extension Double: Arithmetic {} 
extension Float: Arithmetic {} 


class Expr<T:Arithmetic>{ 
    let operand1: T 
    let operand2: T 
    let arithmeticOperator: Character 

    init(a operandA:T, b operandB:T, o arithmeticOperator:Character) { 
    operand1 = operandA 
    operand2 = operandB 
    self.arithmeticOperator = arithmeticOperator 
    } 

    func calculate() -> T? { 
    switch arithmeticOperator{ 
     case "+": 
     return operand1 + operand2 
     case "*": 
     return operand1 * operand2 
     case "-": 
     return operand1 - operand2 
    default: 
     return nil 
    } 
    } 
} 

var expr = Expr(a: 2, b: 5, o: "+"); 
expr.calculate(); 
+0

謝謝。這看起來很整齊。儘管如此,我並不完全確定協議「算術」中方法的用法。你介意擴展嗎? – Codifier 2014-09-27 01:48:11