How to convert a string from a text input into a function in a Scala

后端 未结 1 494
有刺的猬
有刺的猬 2021-01-27 02:10

I am creating a GUI using Scala which should play a signal dependent on the algorithm but into the textField, eg. sin(2*Pi*400*t). The playing function works perfectly, however

相关标签:
1条回答
  • 2021-01-27 02:25

    You want to compile the line of code that the user enters, with some useful preamble.

    I haven't done this so I don't have a snippet handy (but try searching), but you can embed the REPL, have it compile the line of code, and then extract the result.

    Here is a snippet that uses ILoop to get some output, but you want to use IMain to get a result with the result class that wraps the user function.

    import scala.tools.nsc.interpreter.ILoop
    import java.io.StringReader
    import java.io.StringWriter
    import java.io.PrintWriter
    import java.io.BufferedReader
    import scala.tools.nsc.Settings
    
    object FuncRunner extends App {
    
      val line = "sin(2 * Pi * 400 * t)"
    
      val lines = """import scala.math._
        |var t = 1""".stripMargin
    
      val in = new StringReader(lines + "\n" + line + "\nval f = (t: Int) => " + line)
      val out = new StringWriter
    
      val settings = new Settings
    
      val looper = new ILoop(new BufferedReader(in), new PrintWriter(out))
      val res = looper process settings
      Console println s"[$res] $out"
    }
    
    0 讨论(0)
提交回复
热议问题