lundi 26 juin 2023

Scala: Convert string to lambda

I want to be able to parse strings like "x => x + 1" and be able to actually use it as a lambda function like this:

    val string = "x => x + 1"
    val lambda = parseLambda(string)
    val numbers = List(1, 2, 3)
    val result = numbers.map(lambda) // Should be [2, 3, 4]

I have the following implementation for the parseLambda function:

  def parseLambda(string: String): Any => Any = {
      val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
      val tree = toolbox.parse(string)
      val lambdaFunction = toolbox.compile(tree)().asInstanceOf[Any => Any]
      lambdaFunction
  }

It works for strings like "(x: Int) => x * 2" or "(s: String) => s.split(" ")" but if I omit the types e.g. "x => x * 2" or "s => s.split(" ")" I get the following error

';' expected but '=>' found.

Is there a way to be able to omit the types in the string? Any help would be appreciated!





Aucun commentaire:

Enregistrer un commentaire