使用面向协议的二叉树优雅地建模和可视化算术和逻辑表达式。
Arithmetic and logical expressions elegantly modeled and visualized using protocol-oriented binary trees with value semantics.
UIView
s, and observe these animations using the Xcode Playground Live View feature.The principal focus of this project is to demonstrate the structure and evaluation of arithmetic and logical expressions in an elegant, expressive way. Thanks to Swift’s powerful ExpressibleBy*Literal
protocols and operator overloading, we can write code like this:
let expression: ArithmeticExpression<Int> = 2*(1+3)-8/4
and in doing so create the full tree representing this expression, which in turn can be visualized in an Xcode Playground via QuickLook:
Furthermore, we can animate the evaluation of this expression by calling animateEvaluation(of:)
in a Playground page. We can observe this animation in the Playground’s Live View:
In addition to arithmetic expressions, logical expressions can be similarly created, viewed, and animated.
let expression: LogicalExpression = !(true || false) && false || !true
As a simple demonstration of the power of protocol-oriented programming, I’ve also implemented a couple of other tree structures, including a traditional binary search tree and a red-black tree, which can be visualized with QuickLook.
While a brief outline of the project’s contents is provided in the section above, this is a Playground-based project and ultimately better demonstrated than explained:
Expressions is released under the MIT license. See LICENSE for details.
If you find this project to be a useful tool in learning or teaching expressions or binary trees, please reach out to me on Twitter—I’d love to hear from you.