code
ScalaCollider – saving presets with json
On 20, Jun 2011 | No Comments | In code, Uncategorized | By admin
Sometimes it is useful to save presets when working with ScalaCollider. In Supercollider this is usually done with
writeArchive
and
readArchive
, which can be called on any object that does not contain open functions. After review several possibilities to do the same in scala, I found that the easiest is to use lift-json for JSON parsing and generation. JSON is a human readable format, which is quite convenient.
The easiest way to save a preset would be using case classes to hold the data, since lift-json can automatically serialize and deserialize them:
import java.io.{FileWriter} import net.liftweb.json._ import net.liftweb.json.Serialization.{write,read} import scala.io.Source._ object TestJsonSerialization { def main(args: Array[String]) { implicit val formats = DefaultFormats case class Person(name: String, address: Option[String], num:List[Int]) case class Container(persons:List[Person]) val people = Container(List(Person("joe", None, List(1,2,3,4)), Person("jack", Some("NY grand central"), List(5,6,7,8)))) //write values to disk val fw = new FileWriter("test.txt") fw.write(write(people)) fw.close() //get values back val jsonString = fromFile("test.txt").mkString println(pretty(render(parse(jsonString)))) println(read[Container](jsonString)) } }
To compile the example with sbt use this project file:
import sbt._ class JSONProj(info: ProjectInfo) extends DefaultProject(info) { val json = "net.liftweb" %% "lift-json" % "2.3" }
Scala pattern matching and variables
On 16, Jun 2011 | No Comments | In code, Uncategorized | By admin
Today I was debugging some scala code for more than one hour. Turns out that if you use a variable in the pattern you are matching you need to put it in back ticks:
val thing = 3 4 match { case thing => println("bingo") }
This code will match because thing will just became a new variable that is a container for whatever values are being matched.
val thing = 3 4 match { case `thing` => println("bingo") case _ => println("no match") }
This code on the other hand will not match, because the variable thing is used, whose content is 3.
scala compiled to LLVM and Scala.react
On 15, Jun 2011 | No Comments | In code | By admin
Today found a paper submitted at scala days 2011 on “Compiling Scala to LLVM” . That would probably give native speed to scala programs. I will keep following the development of this.
Also interesting is the paper on “Scala.react: Embedded Reactive Programming in Scala” , also from scala days 2011.
- « Previous
- 1
- 2
- 3