Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created September 24, 2008 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymnk/12508 to your computer and use it in GitHub Desktop.
Save ymnk/12508 to your computer and use it in GitHub Desktop.
import jp.takeda_soft.examples.{Plotter, SButton}
import java.lang.Math._
import javax.swing.JFrame
import java.awt.BorderLayout
import scala.concurrent.ops.spawn
import scala.tools.nsc.Properties
/**
* This program will read anonymous functions in Int=>Int from stdin.
* After compiling and loading them dynamically, the 2D graph will be
* rendered with them.
*
* This program expects Scala 2.7.2 RC* with scala-compiler.jar and
* to be compiled with Plotter.scala[1] and CompileAndLoad2.scala[2].
*
* [1] http://gist.github.com/11187
* [2] http://gist.github.com/12506
*/
object DynamicPlotter extends Application{
// This program expects Scala 2.7.2 environment.
if(!Properties.versionString.startsWith("version 2.7.2")){
exit
}
val f = new {
private var current = -1
private var fl = List[Int=>Int]()
def next:Int=>Int = synchronized {
current = if(current == fl.length - 1) 0 else current + 1
fl(current)
}
def += (f:Int=>Int) = synchronized{ fl=f::fl; current = -1 }
}
f += (x=>x)
f += (x=>x*x/200)
f += (pow(_,3).toInt/40000)
f += (x=>(100*sin( 3.14 * x /180 )).toInt)
f += {case x if( x >= 0 ) => x
case x => abs(x)}
f += {case 0 => Int.MaxValue
case x => 200/x}
f += (x => x % 20 match {case 0 => x
case _ => 0})
val f7:Int=>Int = {case x if(x > 0) => f7(x-1) - 1
case x if(x < 0) => f7(x+1) + 1
case _ => 0}
f += f7
val frame = new JFrame {
val plotter = new Plotter(f.next)
val button = new SButton("change function", {
plotter.setFunc(f.next)
repaint()
})
getContentPane().add(button, BorderLayout.SOUTH)
getContentPane().add(plotter)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setBounds(10, 10, 400, 400)
setTitle("function plotter")
show
}
def loop(code:String) {
if(code==null) return
CompileAndLoad2.compileAndLoad(code) match {
case Right(err) => println(err)
case Left((typ, _f:Function1[_,_])) if(typ=="(Int) => Int") => {
f += _f.asInstanceOf[Int=>Int]
frame.plotter.setFunc(f.next)
frame.repaint()
}
case Left((_, _)) => { println("unexpected type") }
}
loop(read)
}
def read = {
print("> ")
Console.readLine
}
spawn { loop(read) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment