davedelong / DDMathParser

String → Number
MIT License
854 stars 153 forks source link

Can't seem to get Custom Functions to work #141

Closed jungalwala closed 6 years ago

jungalwala commented 6 years ago

Hi, I am using Xcode 9 with Swift 3.2 and I am trying to create a custom function. Here is a snapshot of my code (note the function is actually stolen from your code base):

var evaluator = Evaluator()

let randomX = Function(name: "randomX", evaluator: { state throws -> Double in

        var argValues = Array<Double>()
        for arg in state.arguments {
        let argValue = try state.evaluator.evaluate(arg, substitutions: state.substitutions)
        argValues.append(argValue)
        }

        let lowerBound = argValues.count > 0 ? argValues[0] : Double.leastNormalMagnitude
        let upperBound = argValues.count > 1 ? argValues[1] : Double.greatestFiniteMagnitude

        let range = upperBound - lowerBound

        return (drand48().truncatingRemainder(dividingBy: range)) + lowerBound
})

do {
      try evaluator.registerFunction(randomX)           
} catch let error {
      print (error)
}
let value = try formula.evaluate(using: evaluator, substitutions)

But I constantly get the following error:

MathParserError(kind: MathParser.MathParserError.Kind.unknownFunction("randomX"), range: Range(0..<20))
DetailViewController::calculateFormula - error evaluating formula: randomX('160','170')

I looked inside evaluator->functionSet->functionsByName and I see 'randomX' in the list (offset 17).

[17]    (key: String, value: MathParser.FunctionRegistration)   
key String  "randomX"   
_core   _StringCore 
value   MathParser.FunctionRegistration 0x79165190
names   Set<String> 
[0] String  "randomX"   
_core   _StringCore 
_baseAddress    UnsafeMutableRawPointer?    (_rawValue = 0x00261c89 "randomX")  some
_countAndFlags  UInt    7
_owner  Swift.AnyObject?    nil none
function    MathParser.FunctionEvaluator    0x000e7af0 Hub`closure #1 (MathParser.EvaluationState) throws -> Swift.Double in variable initialization expression of Hub.DetailViewController.randomX : MathParser.Function at DetailViewController.swift:82

So I am unsure why MathParser is reporting "unknownFunction("randomX")

Please help!

Jay

jungalwala commented 6 years ago

I found my issue, it turns out that having mixed case for a function name was the issue. If I converted all references of "randomX" to "randomx" things worked.