Thursday 2 June 2011

Monday 28 February 2011

Clojure

In collaboration with Mr Yannick Malins as a result of having too much time in the evenings of a ski holiday. Not actual Scala but close enough.

Recurses thru a directory looking for 'test.txt' files and cats the result to the output file and stdout.


(import
'(java.io File FileWriter BufferedReader FileReader))

(def myfile (new File "C:\temp\source\"))
(def myfile2 (new File "C:\temp\out.txt"))

(defn recurse-files [file]
(if (.isDirectory file)
(apply str (map recurse-files (.listFiles file)))
(when (= (.getName file) "test.txt")
(let [reader (new BufferedReader (new FileReader file))]
(apply str (map
#(str (.getParent file) "/" % \newline)
(line-seq reader)))))))

(doto (new FileWriter myfile2)
(.write (recurse-files myfile))
(.close))

(recurse-files myfile)

Wednesday 7 July 2010

Scala + Lift tutorial

If I go back to Scala heres a nice Lift tutorial link:

http://blog.m1key.me/2010/07/rest-with-scalas-lift-framework-part-1.html

Saturday 11 July 2009

Implicits (base converter)

Defining a method as 'implicit' means that it becomes global to that package. Use with extreme care!!

Here is an integer base converter which I wrote:
Note how we can now call methods on the integers themselves

object Types {
case class NumberConverter(val i : Int) {
def octal = BaseBuilder(i, 8)
def hex = BaseBuilder(i, 16)
def mybase(base : Int) = BaseBuilder(i, base)
}

def BaseBuilder(i : Int, base : Int) : String = {
i match {
case 0 => ""
case _ => BaseBuilder(i/base, base) + baseToCharacter(i % base)
}
}

def baseToCharacter(i : Int) : String = {
return "" + {
if ( (0 to 9).contains(i) ) {
i
} else {
(i + 55).toChar
}
}
}

implicit def baseConverter(i : Int) : NumberConverter = NumberConverter(i)

def main(args : Array[String]) : Unit = {
println( 29 )
println( 29.hex )
println( 29.octal )
println( 15.mybase(16) )
println( 129.mybase(2) )
}
}

Sunday 5 July 2009

Actors & Concurrency

Actors are the first thing I've found where Scala definently kicks Java's ass.

We dont use 'Synchronized' anymore. Instead each 'Actor' has a sort of 'mail box' or 'to do list' that other processes can call either Synchronously or Asynchronously.

code:


package scalaexperiment

import scala.actors._
import Actor._

case class SayHi
case class SayThis(s : String)
case class GetActorStatus

object Actors {
def main(args : Array[String]) : Unit = {
val man = new Man1

(0 to 3).foreach( a => {
man ! SayHi //Asynchronous calls
man ! SayThis("gobblydgook "+a)
man ! Actors
})

println("I am going to wait here...")
val count = man !? GetActorStatus //Sychronous call
println("....For you to tell me how many times you were called: "+count)
}
}

class Man1 extends Actor {
val s = "From Actor> "
var count = 0;
def act = loop {
react {
count += 1
doOptions
}
}

def doOptions : PartialFunction[Any, Unit] = {
case GetActorStatus => reply(count)
case SayHi => println(s+"hi")
case SayThis(a) => println(s + a)
case _ => println(s+"Dont know what you asked me to say ")
}
this.start
}


Tip: Dont forget to call 'start' on your Actors.

Additional:
! = Asynch call
!? = Synch call (wait for me!)
!! = Asynch call that returns a Future[T] value
reactWithin(n) = react within n milliseconds.
!?(n, param) = wait n seconds for result.

Thursday 2 July 2009

More Partial Functions

Here I am defining a couple of PartialFunctions and using them:

def main(args :Array[String]) :Unit = {

def f1 : PartialFunction[List[String], String] = {
case "a" :: rest => "I got an A"
}
def f2 : PartialFunction[List[String], String] = {
case "a" :: "b" :: rest => "I got an A and the next letter is a B"
}
def f3 = f2 orElse f1

println( handleRequest2( "a"::"c"::"a"::"b"::Nil)(f3) )
}

def handleRequest2(req : List[String])
(exceptions : PartialFunction[List[String], String]) : String = {
if (req.isEmpty) {
""
} else if (exceptions.isDefinedAt(req)) {
exceptions(req) + "\n" + handleRequest2( req.tail )(exceptions)
} else {
"Normal handle "+req.head+" ..done" + "\n" + handleRequest2( req.tail(exceptions)
}
}


Output [is unsurprisingly]:

I got an A
Normal handle c ..done
I got an A and the next letter is a B
Normal handle b ..done