I need Help I have a simple math expression parser:
public indirect enum Expr {
case variable // could take name as associated type to support multiple vars
case const(Decimal)
case negate(Expr)
case sum([Expr])
case product([Expr])
case quotient(Expr, Expr)
case power(Expr, Decimal)
}
public extension Expr {
static prefix func -(expr: Expr) -> Expr { .negate(expr) }
static func +(lhs: Expr, rhs: Expr) -> Expr { .sum([lhs, rhs]) }
static func -(lhs: Expr, rhs: Expr) -> Expr { .sum([lhs, .negate(rhs)]) }
static func *(lhs: Expr, rhs: Expr) -> Expr { .product([lhs, rhs]) }
static func /(lhs: Expr, rhs: Expr) -> Expr { .quotient(lhs, rhs) }
static func ^(lhs: Expr, rhs: Decimal) -> Expr { .power(lhs, rhs) }
}
extension Expr: ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral {
public init(integerLiteral: Int64) {
self = .const(Decimal(integerLiteral))
}
public init(floatLiteral: Double) {
self = .const(Decimal(floatLiteral))
}
}
It works great with expressions:
for example:
let x: Expr = .variable
let expr: Expr = 3*(x+5)
print(expr)
prints:
product([SymbolicDifferentiator_Sources.Expr.const(3), SymbolicDifferentiator_Sources.Expr.sum([SymbolicDifferentiator_Sources.Expr.variable, SymbolicDifferentiator_Sources.Expr.const(5)])])
But I want to parse expressions entered with Command Line (as I String):
I've tried
let stringWithMathematicalOperation: String = "5*5" // Example
let exp: NSExpression = NSExpression(format: stringWithMathematicalOperation)
let result: Expr = exp.expressionValue(with:nil, context: nil) as! Expr
But it gives me an error on the last string: Could not cast value of type '__NSCFNumber' (0x1fe417d18) to 'SymbolicDifferentiator_Sources.Expr' (0x1070e4510).
How can I convert String entered in Command Line to expression and cast it to my Expr indirect enum?