scala
Some examples of pure functional programs that actually do something.
On 17, Jul 2011 | No Comments | In code | By admin
I’ve been struggling with functional programming lately. The part about using pure functions is very easy for me to get, what was/Is difficult is to understand how does a pure program contact with the outside world and manages to keep state.
I then studied a bit about the IO monad, and I managed to understand how to contact with the outside world. The final piece of the puzzle that I’m still missing is out to piece all this together and how to keep the state in a functional way. I’ve coded some very simple examples to teach myself how these things are done. The examples are scala code and use the scalaz library.
In this first example I just read one line at a time from the prompt and then write it back. The app will do this forever until it is killed. The part that causes it looping forever is done by the recursive function forever, which just repeats the same action over and over:
def forever(theIO:IO[Unit]):IO[Unit] = theIO >>=| forever(theIO)
I find it quite magical way the way this compact syntax encapsulates the action of just doing something over and over again.
import scalaz._ import Scalaz._ import effects._ /* This program just echo the input */ object Test1 { def forever(theIO:IO[Unit]):IO[Unit] = theIO >>=| forever(theIO) def functionalMain = { forever(for( line
On the second example I read one line from the prompt and then add it to a list. I was looking for ways to do this without storing this list anywhere. The method that causes the looping in this case is slightly more complicated, because it has to keep propagating an argument forever, by just passing it to the next action. This way we manage to keep state, a list with all the previous strings, without actually storing this list anywhere. Again, I find this quite magical.
import scalaz._ import Scalaz._ import effects._ object Test2 { def getStringAndAddToList(list:List[String]):IO[List[String]] = for( line (A=>IO[A])):A=>IO[A] = makeIO(_) >>= forever(makeIO) def functionalMain = { val action = forever(getStringAndAddToList _) action(Nil) } def main(args: Array[String]) { functionalMain.unsafePerformIO } }
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.