Skip to content

Feature request: run-time variables and functions #54

@EgorBron

Description

@EgorBron

It would be nice if the library supported variable and math function creation during evaluation.

To keep backward compatibility, we could introduce a new function like evalExtended(String): KevalResult or something similar.

KevalResult would be a class that holds the evaluated value, or both the original expression and a callable function:

class KevalResult {
    val value: Double?
    operator fun invoke(vararg args: Double): Double { ... }
}

Given code like this:

var b = 32.0
val keval = Keval.create {
    includeDefault()
    function {
        name = "someFunc"
        implementation = { 42.0 }
    }
    function {
        name = "getB"
        implementation = { ++b }
    }
}

val kevalExpr = """
a = someFunc() * PI % getB()
b = getB()
f(x) = a*x + b
f(10)
"""

keval.evalExtended(kevalExpr).value // 341.6944...

In this example:

  • We define variables a and b, which are evaluated when defined.
  • We define a function f with one argument x.
  • We then call f(10), which evaluates the function.

Expected behavior of evalExtended():

  • If the last line is an expression, evalExtended() returns a KevalResult with a non-null value. Invoking this result returns the value.
  • If the last line is a variable definition, the behavior is the same as above.
  • If the last line is a function definition, the value in the returned KevalResult is null, and invoking the result will evaluate and return the function result.

What do you think about this approach?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions