[英]Swift : Recursively calling a function with an enum type as a parameter
I found this code at apple swift documentation 我在Apple Swift文档中找到了此代码
indirect enum ArithmeticExpression {
case Number(Int)
case Addition(ArithmeticExpression, ArithmeticExpression)
case Multiplication(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)
}
}
// evaluate (5 + 4) * 2
let five = ArithmeticExpression.Number(5)
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
print(evaluate(product))
// prints "18"
i don't quit understand how the recursion is happening in here and why a constant declaration is being declared as a parameter in the return statement in the returning line ? 我不退出来了解递归在这里是如何发生的,为什么在返回行的return语句中将常量声明声明为参数?
Think of it as a tree. 把它想像成一棵树。 Nodes=Expressions. 节点=表达式。 Constants=Leaves. 常数=叶。
(image source ruslanspivak.com) (图片来源ruslanspivak.com)
While traversing it - you examine each of the two operands. 遍历它时-检查两个操作数中的每一个。 If it's an expression, you need to compute it, so you call on 'evaluate' with this operand. 如果它是一个表达式,则需要对其进行计算,因此您可以使用此操作数调用“求值”。 If it's a constant, think of it like a result - it's just a number, so no more calculations are needed. 如果它是一个常数,则将其视为一个结果-它只是一个数字,因此不需要更多的计算。 In the end, we ALWAYS get to a constants (=leaves) it is then when the the stack starts to fold and the values results return "up" in the tree to add up to the total result. 最后,我们总是获得一个常量(=叶),然后当堆栈开始折叠且值结果在树中返回“ up”时,便得出总结果。
For more diving into the subject I recommend googling "binary expression tree". 为了进一步研究该主题,我建议使用Google搜索“二进制表达式树”。
(By the way, the code example does not tend for priorities. The multiplication is computed before the addition only because the order of calls. If we really wanted to take care of priorities : eg "(", ")" over "*" , "/", a stack for operations would have been needed here.) (顺便说一下,该代码示例不倾向于优先级。乘法运算仅在加法之前进行,仅是因为调用的顺序。如果我们真的想照顾优先级,例如,“ *”上的“(”,“)” ,“ /”,此处需要用于操作的堆栈。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.