<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xebia Blog &#187; Arjan Blokzijl</title>
	<atom:link href="http://blog.xebia.com/author/ablokzijl/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Scala actors for the enterprise: introducing the Akka framework</title>
		<link>http://blog.xebia.com/2009/10/22/scala-actors-for-the-enterprise-introducing-the-akka-framework/</link>
		<comments>http://blog.xebia.com/2009/10/22/scala-actors-for-the-enterprise-introducing-the-akka-framework/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 10:21:16 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[Akka]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=3264</guid>
		<description><![CDATA[Last week me and some of my colleagues had the pleasure of being on the receiving end of an excellent training given by Jonas Bonér. The topic was his new pet project: the Akka framework. Perhaps you&#8217;ve played around with Scala lately, and also have taken the first steps in using its Actor library. Simply [...]]]></description>
			<content:encoded><![CDATA[<p>Last week me and some of my colleagues had the pleasure of being on the receiving end of an excellent training given by <a href="http://jonasboner.com/">Jonas Bonér</a>. The topic was his new pet project: <a href="http://wiki.github.com/jboner/akka">the Akka framework</a>. Perhaps you&#8217;ve played around with Scala lately, and also have taken the first steps in using its Actor library. Simply stated, an Actor is a unit of execution that (usually asynchronously) processes messages and encapsulate their state. An actor does not expose its state, and messages are processed sequentially. The <a href="http://en.wikipedia.org/wiki/Actor_model">Actor model</a> has been around for quite some time, but today the best-known Actor implementation is Erlang.<br />
The Actor model has been implemented in the standard Scala library by Philipp Haller (for the interested reader, a solid reference is for instance <a href="http://lamp.epfl.ch/~phaller/doc/haller06jmlc.pdf">this article</a> explaining how actors in Scala work). In most Actor examples written in Scala, it is not uncommon to find only EchoActors, PingPongActors, and FibonacciSolvingActors. Nice examples, but perhaps you might wonder if they are of any use in enterprise Scala at all. Next to this, if you&#8217;re interested in concurrent, message passing processing models, STM&#8217;s, NoSQL data stores, and occasionally wonder what the future in enterprise computing might bring, than Akka might be just the framework you&#8217;re looking for. This blog is intended to provide a brief introduction into one feature of this framework: Akka&#8217;s supervisor Actors. It is mostly based on the knowledge extracted from Jonas during the training, and I hope to whet your appetite for it.</p>
<p><span id="more-3264"></span><br />
First of all, Akka is likely to support what Ray Racine has coined to be a &#8216;System of Service&#8217;. I&#8217;m quoting him here literally from the scala mailing list:</p>
<blockquote><p>Its not too far of stretch to say commercial vendors, and most frameworks are very System Of Record oriented.  Need to build a new app to maintain X.<br />
Install RDB, app server, select O/R mapping and GUI form framework, place warm bodies in front of drag and drop IDEs and go for it.</p>
<p>A System Of Service must service 1,000s of requests per second in millisecs, 24/7/365 with 99.99 % reliability e.g. a pricing service.  The business<br />
logic has to run in microseconds.  Your favorite O/R mapping framework hasn&#8217;t even initiated a JDBC call, heck hasn&#8217;t even allocated a connection from the pool and its already exhausted its 1 ms in allotted time.</p>
<p>An item may undergo a few 10s of price changes a year on the System Of Record, yet that item&#8217;s price may be served 100,000 times for each change on the System Of Service&#8217;.</p></blockquote>
<p>In other words a System of Service is a system designed to have extreme throughput, and almost zero downtime. It may not be your everyday CRUD application, but if you need to build them, it is nice to know of some framework that supports it. In response to Ray Racine&#8217;s post Jonas Bonér posted his vision for the Akka framework. These posts provide plenty of highly interesting reading material, and can be found <a href="http://www.nabble.com/Akka-Actor-Kernel---Re:--scala--Lift-and-Goat-Rodeo-td24124685.html">here</a>.</p>
<p>Akka is therefore meant to be a kind of framework that supports a System Of Service application. It has many features, too much to cover all at once, and therefore we will start of with having a look at Akka&#8217;s actors supervisor capabilities.<br />
Akka has an Actor model with supervision trees, based on Erlang&#8217;s <a href="http://www.erlang.org/doc/design_principles/part_frame.html">OTP design principles</a>. Supervisors are processes that monitor a set of workers, that do the actual processing. The basic idea of a supervisor is that it should keep its child processes alive by restarting them when necessary. A worker is an Actor, that receives and processes a message. When a worker dies abnormally (by throwing an Exception), it is up to the supervisor to determine what to do. It may decide to restart the worker, and try to process the message again, with a maximum number of retries set. The approach is to expect that failures can and eventually will happen. Instead of trying to prevent this, the idea is to <a href="http://letitcrash.com/">Let it crash</a> (TM Jonas Bonér), reset the worker to a stable state, restart it. This idea has served Ericsson well in building highly fault tolerant, distributed message passing software. We can now profit from this idea in Scala as well via Akka.</p>
<p>In order to achieve this, Akka has its own version of the Actors library, that have more &#8216;system of service&#8217; features than the standard Actors library found in the Scala distribution. To demonstrate a simple example of a supervisor class, here&#8217;s some sample code to demonstrate the idea. First, we start of with a simple Actor:</p>
<pre class="brush: scala; title: ; notranslate">
import se.scalablesolutions.akka.config.ScalaConfig._
import se.scalablesolutions.akka.actor.{OneForOneStrategy, Actor}

sealed trait Message

case class Supervise(worker: Worker) extends Message

case class DoWork(work: Work) extends Message

case object Die extends Message

class Worker(workerName:String) extends Actor {
lifeCycleConfig = Some(LifeCycle(Permanent, 100))

def receive: PartialFunction[Any, Unit] = {

case DoWork(work:String) =&gt;
log.debug(&quot;start working... at: &quot; + work)

case Reset =&gt;
log.info(&quot;%s has been reset&quot;, toString)

case Die =&gt;
log.debug(&quot;Dying...&quot;)
throw new RuntimeException(&quot;I'm dead: &quot; + this.toString)

case other =&gt;
log.error(&quot;Unknown event: %s&quot;, other)
}

override def preRestart(reason: AnyRef, config: Option[AnyRef]) {
log.debug(&quot;pre-restarting &quot; + this)
}

override def postRestart(reason: AnyRef, config: Option[AnyRef]) {
log.debug(&quot;post-restarting &quot; + this)
}

override def toString = &quot;[&quot; + workerName + &quot;]&quot;
</pre>
<p>As regards to sending message passing, an Akka actor follows the same API as the &#8216;normal&#8217; Scala ones: you can send a message to an actor using the ! (pronounced bang) method. This is a &#8216;fire and forget&#8217; message, which is then processed asynchronously by the actor. There are some more options to send messages, but we&#8217;ll skip these for now. In Akka, Actors have to be started explicitly by calling actor.start for it to be able to process any messages. It can be stopped by calling actor.stop.<br />
Compared to the standard Scala actors, the API for processing messages is more limited: there is exactly one method that you must override. This is the receive method, which must return a <a href="http://www.scala-lang.org/docu/files/api/scala/PartialFunction.html">PartialFunction</a>. The receive method uses a pattern match to distinguish between various messages it can process. A pattern match is compiled down to a PartialFunction, which is the return value of the pattern match.<br />
To send messages to actors, we&#8217;ve defined a Message trait, which various case classes that represent the actual messages extend. In principle, you can send any message to an Actor, however, in practice however, the only messages you should send should be immutable. In Scala, case classes and case objects are immutable by default, and thus are a natural fit for this. In this case, we&#8217;ve defined a &#8216;DoWork&#8217; message (all messages extends from the same Message trait), which should set the Worker actor to do something that hopefully will be be of some use. When the worker receives a Die message, it will throw an exception. This is a somewhat silly example of course, but hopefully it demonstrates the idea.</p>
<p>So far, nothing special, apart perhaps the pre- and postRestart methods, and the field lifeCycleConfig = Some(LifeCycle(Permanent, 100)). This is configuration for Akka&#8217;s actors supervisor hierarchy capabilities. To see further how this works, let&#8217;s code up a supervisor:</p>
<pre class="brush: scala; title: ; notranslate">
import se.scalablesolutions.akka.actor.OneForOneStrategy

object WorkerSupervisor extends Actor {
trapExit = true
faultHandler = Some(OneForOneStrategy(3, 100))

def receive: PartialFunction[Any, Unit] = {
case DoSupervise(worker:Worker) =&gt;
log.info(&quot;Supervising worker: &quot; + worker)
startLink(worker)

case unknown =&gt;
log.error(&quot;Unknown event: %s&quot;, unknown)
}
}
</pre>
<p>Our supervisor is also an Akka actor (in this case, it is an object, i.e. a singleton in Scala), that processes &#8216;DoSupervise(worker)&#8217; messages. It handles this message by starting to supervise the worker by the invoking the &#8216;startLink(worker)&#8217; method, which is defined in the Actor class. This will add our worker to the list of its linked actors, and also handles starts the linked Actor at the same time. Of cours the nice thing is that the Actor class will handle thread safety for us, so we don&#8217;t need to worry about any multithreading issues here.<br />
The linking achieves exactly what it promises: if a linked Actor (the worker in our case) throws an exception, the supervising actor (our WorkerSupervisor) will be notified of this. For this, it is necessary to override the variable trapExit, and set it to true. It may then decide what to do based on the fault handler strategy Strategy that is defined by defining the faultHandler variable. There are currently two strategies: OneForOne, meaning that only the actor that has crashed will be restarted, and AllForOne, meaning all linked actors (including the crashed one) will be restarted. This is also where the lifeCycleConfig defined on our worker Actor comes in. LifeCycle(Permanent, 100) means our actor has a permanent LifeCycle and will always be restarted in case of an exception. The preRestart and postRestart are callback methods that may be overridden by the supervised actor to do some initialization work when it is restarted. Note that our supervised actors will probably be some kind of application services, instead of our useless Worker actor, and therefore may really need to do some usefull initialization work like setting up resources, connections, etc, in order to operate properly.</p>
<p>Instead of manually coding a Supervisor like we&#8217;ve done, there&#8217;s an alternative in setting up a set of linked services in a more declarative way by extending Akka&#8217;s SupervisorFactory class, as follows:</p>
<pre class="brush: scala; title: ; notranslate">
import se.scalablesolutions.akka.actor.SupervisorFactory
import se.scalablesolutions.akka.config.ScalaConfig.{LifeCycle, SupervisorConfig, RestartStrategy, Supervise, OneForOne, Permanent}

class MySupervisorFactory extends SupervisorFactory {

val worker = new Worker(&quot;worker-1&quot;)

override protected def getSupervisorConfig: SupervisorConfig = {
SupervisorConfig(
RestartStrategy(OneForOne, 3, 10),
Supervise(
worker,
LifeCycle(Permanent, 1000)) :: Nil)
}
}

object factory extends MySupervisorFactory
</pre>
<p>This defines a list of supervised actors (in our case, a one element list containing our worker) and then use the following code:</p>
<pre class="brush: scala; title: ; notranslate">
val supervisor = factory.newSupervisor
supervisor.startSupervisor
</pre>
<p>which will link all workers to one supervisor (defined within the framework) and (re)start them based on the configured strategy. You can therefore pick your preferred way of configuring.</p>
<p>All that remains is to see whether it actually works. For this we need a small simulation class, defined as follows:</p>
<pre class="brush: scala; title: ; notranslate">
class Simulation {

var worker:Worker = _

@Before
def setUp = {

worker = new Worker(&quot;worker-1&quot;)
WorkerSupervisor ! DoSupervise(worker)
}

@After
def tearDown = {
WorkerSupervisor.stop
}

@Test
def testSuperviseWorker = {
Thread.sleep(500)
println(&quot;\n===&gt; start working&quot;)

worker ! DoWork(&quot;Some work&quot;)
Thread.sleep(500)

worker ! Die
Thread.sleep(1000)

worker ! DoWork(&quot;Some more work&quot;)

println(&quot;\n===&gt; finished&quot;)

}
}
</pre>
<p>Running this shows output like the following:</p>
<pre>INF [20091020-19:28:25.242] akka: Supervising worker: [worker-1]
DEB [20091020-19:28:25.242] akka: Linking actor [[worker-1]] to actor
[Actor[1256143591312:class akka.supervision.WorkerSupervisor$]]

===&gt; start working
DEB [20091020-19:28:25.750] akka: start working... at: Some work
DEB [20091020-19:28:26.249] akka: Dying...
java.lang.RuntimeException: I'm dead: [worker-1]
	at akka.supervision.Worker$$anonfun$receive$1.apply(Worker.scala:48)
	at akka.supervision.Worker$$anonfun$receive$1.apply(Worker.scala:38)
	at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:38)
	at se.scalablesolutions.akka.actor.Actor$class.transactionalDispatch(Actor.scala:496)
	at se.scalablesolutions.akka.actor.Actor$class.invoke(Actor.scala:461)
	at akka.supervision.Worker.invoke(Worker.scala:33)
	at se.scalablesolutions.akka.actor.ActorMessageInvoker.invoke(Actor.scala:39)
	at se.scalablesolutions.akka.reactor.EventBasedThreadPoolDispatcher$$anon$1$$anon$2.
            run(EventBasedThreadPoolDispatcher.scala:99)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:619)
DEB [20091020-19:28:26.260] labs: pre-restarting [worker-1]
INF [20091020-19:28:26.262] labs: Restarting actor [class akka.supervision.Worker]
                                                         configured as PERMANENT.
DEB [20091020-19:28:26.265] labs: post-restarting [worker-1]

===&gt; finished
DEB [20091020-19:28:27.251] labs: start working... at: Some more work

Process finished with exit code 0</pre>
<p>Which indeed shows that our rudimentary supervisors work.<br />
This concludes the introduction into Akka&#8217;s supervising actors. There is much more that Akka&#8217;s actors are capable of than shown here (remoting, transactions, STM, cassandra and mongo backend, to name just a few), but those are materials for future blogs. It may be perhaps a bit much to take all at once, as it requires to learn an API that is likely to be unknown to most of us. I won&#8217;t deny that the Akka framework certainly has some learning curve, but the reward is great once you get the hang of it.<br />
Akka is relatively young and still evolving. If you&#8217;re interested in its future directions, check out the <a href="http://www.assembla.com/spaces/akka/tickets?milestone_id=117393&amp;tickets_report_id=1">roadmap for the 0.6 release</a>.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/10/22/scala-actors-for-the-enterprise-introducing-the-akka-framework/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F10%2F22%2Fscala-actors-for-the-enterprise-introducing-the-akka-framework%2F&amp;title=Scala%20actors%20for%20the%20enterprise%3A%20introducing%20the%20Akka%20framework" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/10/22/scala-actors-for-the-enterprise-introducing-the-akka-framework/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Functional bowling in Scala</title>
		<link>http://blog.xebia.com/2009/07/25/functional-bowling-in-scala/</link>
		<comments>http://blog.xebia.com/2009/07/25/functional-bowling-in-scala/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 10:54:31 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[General]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2723</guid>
		<description><![CDATA[I have read about implementing the bowling game XP-style many years ago in Robert Martin&#8217;s book &#8216;Agile Software Development&#8217;. The episode can be found online as well. Recently he has recently been learning Clojure and attempted to implement the bowling game in Clojure. It is a nice exercise, and although I like Clojure, I do [...]]]></description>
			<content:encoded><![CDATA[<p>I have read about implementing the bowling game XP-style many years ago in Robert Martin&#8217;s book &#8216;Agile Software Development&#8217;. The episode can be found <a href="http://www.objectmentor.com/resources/articles/xpepisode.htm">online</a> as well.<br />
Recently he has recently been learning <a href="http://clojure.org/">Clojure</a> and <a href="http://blog.objectmentor.com/articles/2009/07/19/uncle-bob-jsps-learning-clojure">attempted to implement</a> the bowling game in Clojure.<br />
It is a nice exercise, and although I like Clojure, I do not regard myself capable in any way to repeat such an attempt. Apart from that Stuart Halloway, author of the excellent &#8216;Programming in Clojure&#8217; book, has already <a href="http://blog.runcoderun.com/post/145675117/tdd-in-a-functional-language-uncle-bobs-bowling">done this</a> in a much better way than I ever could. I&#8217;m slightly more familiar with Scala, so I thought it would be a nice exercise to try some functional bowling using that. My Scala knowledge is in a deplorable state, stuck at pre-beginner level, so I run the risk of making a complete fool of myself. However I&#8217;ll take the chance and at least try to learn from the experience.</p>
<p><span id="more-2723"></span></p>
<p>First, let&#8217;s re-iterate the rules of bowling:</p>
<blockquote>
<ol>
<li>The game consists of 10 frames. In each frame the player has two opportunities to knock down 10 pins. The score for the frame is the total number of pins knocked down, plus bonuses for strikes and spares.
<li>A spare is when the player knocks down all 10 pins in two tries. The bonus for that frame is the number of pins knocked down by the next roll.
<li>A strike is when the player knocks down all 10 pins on his first try. The bonus for that frame is the value of the next two balls rolled.
<li>In the tenth frame a player who rolls a spare or strike is allowed to roll the extra balls to complete the frame. However no more than three balls can be rolled in tenth frame.
</ol>
</blockquote>
<p>So in some way we need to keep track of frame scores for a game. For simplicity, I&#8217;m just using a sequence of integers that represents a game. Each integer just represents the number of pins knocked down by each throw.<br />
This sequence should be divided, or transformed if you like, into a sequence of frames. I started with something like this:</p>
<pre class="brush: scala; title: ; notranslate">
case class Frame(first:Int, second:Int, third:Int) {
    override def toString() = {&quot;firstThrow: &quot; + first + &quot; secondThrow&quot; + second + &quot; thirdThrow: &quot; + third}
}

def frames(g:List[Int]):List[Frame] = {
    g match {
      case Nil =&gt; Nil
      case x::Nil =&gt; List(new Frame(x, 0, 0))
      case x::xs::Nil =&gt; List(new Frame(x, xs, 0))
      case 10 :: x::xs =&gt; new Frame(10, x, xs.head) :: frames(xs.tail)
      case x::xs::xss if ((x + xs) == 10) =&gt; new Frame(x, xs, xss.head) :: frames(xss.tail)
      case x::xs =&gt; new Frame(x, xs.head, 0) :: frames(xs.tail)
   }
}
</pre>
<p>But this might be an excellent candidate for the <a href="http://thedailywtf.com/Default.aspx">thedailywtf</a>. This surely cannot be the way how to write proper Scala, and apart from that, it&#8217;s not very generic and extensible. So, after thinking about the matter a bit, a second attempt. First of all, why a class when we have functions? A sequence of frames can just be expressed as a list of lists, like so:</p>
<pre class="brush: scala; title: ; notranslate">
def frames(g:List[Int]):List[List[Int]] = {
    if (g.isEmpty) Nil
    else {
    val throws = throws_for_frame(g)
    g.take(throws)::frames(g.drop(throws))
    }
}

def frames(g:List[Int]):List[List[Int]] = {
     if (g.isEmpty) Nil
     else
        g.take(throws_for_frame_score(g))::frames(g.drop(throws_in_frame(g)))
}

def throws_for_frame_score(rolls:List[Int]):Int = {
     if (strike(rolls) || spare(rolls)) 3
     else 2
}

def throws_in_frame(rolls:List[Int]):Int = {
     if (strike(rolls)) 1
     else 2
}

def strike(rolls:List[Int]):Boolean = {
     rolls.headOption.getOrElse(false) == 10
}

def spare(rolls:List[Int]):Boolean = {
     rolls.take(2).foldLeft(0)(_+_) ==10
}
</pre>
<p>Not too bad, if you look at it from a distance some little helper functions like strike and spare even seem to be related to some of the bowling rules defined above. A frame is now just a list consisting of either 2 or 3 elements, depending on whether a strike or spare has been scored. Each element is an integer containing the pins that are knocked down.</p>
<p>Scoring a game now becomes a rather trivial affair, we just take the 10 frames that are bowled and add up the pins scored in each frame. </p>
<pre class="brush: scala; title: ; notranslate">
def score_game(g:List[Int]):Int = {
     framescores(g).foldLeft(0)(_+_)
}

def framescores(game:List[Int]):List[Int] = {
     frames_for(game).take(10).map(l =&gt; l.foldLeft(0)(_+_))
}

def framesThrown(g:List[Int]) = {
     frames(g).length
}
</pre>
<p>In the REPL, you can easily test these functions:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
scala> framesThrown(List(4,5))
res1: Int = 1

scala> framesThrown(List(4,5,10,3,4,6,7,2))
res2: Int = 4

scala> framescores(List(4,5))
res3: List[Int] = List(9)

scala> framescores(List(4,5,6,3))
res4: List[Int] = List(9, 9)

scala> framescores(List(5,5,6,3))
res5: List[Int] = List(16, 9)

scala> framescores(List(5,5,6,3,10,10,3))
res6: List[Int] = List(16, 9, 23, 13, 3)

scala> framescores(List(10,10,10,10))
res4: List[Int] = List(30, 30, 20, 10)
</pre>
</div>
<p>And to satisfy Uncle Bob, some unit tests:</p>
<pre class="brush: scala; title: ; notranslate">
class BowlingTest {

    def repeat[T](n: Int)(what: =&gt; T): List[T] = {
        if (n==0)List.empty
        else what::repeat(n-1)(what)
    }

    @Test
    def scoreForTwoThrows = {
        assertEquals(9, score(List(4,5)))
    }

    @Test
    def strikeShouldGiveTwoExtraThrowsForScore = {
        assertEquals(List(30,30,20,10), framescores(repeat(4)(10)))
        assertEquals(24, score(List(5, 3, 4, 5, 3,4)))
        assertEquals(32, score(List(10, 3, 4, 5, 3)))
    }

    @Test
    def spareShouldGiveOneExtraThrowsForScore = {
        assertEquals(24, score(List(5, 3, 4, 5, 3, 4)))
        assertEquals(30, score(List(5, 5, 4, 5, 3, 4)))
     }

    @Test
    def spareAtEndShouldGiveOneExtraThrowsForScore = {
        assertEquals(60, score(List(4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 6, 5)))
        assertEquals(54, score(List(4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 5, 5)))
     }

    @Test
    def strikeAtEndShouldGiveTwoExtraThrowsForScore = {
        assertEquals(65, score(List(4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 10, 5, 5)))
        assertEquals(54, score(List(4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 5, 5)))
     }

    @Test
    def tears = {
        assertEquals(299, score(List(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9)))
     }

    @Test
    def perfectGameShouldScore300 = {
        assertEquals(300, score(repeat(12)(10)))
    }

    @Test
    def allOnesShouldScore20 = {
        assertEquals(20, score(repeat(20)(1)))
    }
}
</pre>
<p>It&#8217;s still a bit simplistic (for example, framesThrown doesn&#8217;t really check whether a frame is finished, i.e. whether two or three throws have been made, there&#8217;s no validation that the number of pins knocked down cannot be larger than 10, games can have an infinite length, etc, etc). However I&#8217;ll leave it at this for the moment, and will try to perfect it later. It has already been a nice exercise so far in any case. As stated, my Scala knowledge is such that this implementation can most likely be heavily improved upon. If you have suggestions for improvements (or have an implementation of your own) your comments are highly appreciated.</p>
<p><strong>Update</strong><br />
As Ilian Berci has pointed out, my satisfaction at my original attempt was completely misguided. Somehow I managed to misinterpret the bowling rules completely. I managed to get into my mind that a strike would give two extra throws, in each frame. However, if you have once taken up a game of bowling yourself you know that this is complete nonsense. It is only so that the next two throws (which are then part of another frame) contribute to the frame in which the strike is scored. It is only at the tenth frame that the bowler gets an extra frame (consisting of maximum two throws) if he scores a strike at his final games. So, my original framescores function and helper function looked like below:</p>
<pre class="brush: scala; title: ; notranslate">
def frames(g:List[Int]):List[List[Int]] = {
    if (g.isEmpty) Nil
    else {
    val throws = throws_for_frame(g)
    g.take(throws)::frames(g.drop(throws))
    }
}

def throws_for_frame(rolls:List[Int]):Int = {
    if (strike(rolls) || spare(rolls)) 3
    else 2
}
</pre>
<p>which is utterly wrong, since it places all the throws that contribute to a frame score in the same frame (and removes them from the remaining games list). This makes that a game in my original version could take up to 30 throws, instead of the 21 maximum throws possible.<br />
So, in my original version, the framescores functions behaved like this:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
scala> framescores(List(5,5,6,3))
res14: List[Int] = List(16, 3)

scala> framescores(List(10,10,10,10,10))
res15: List[Int] = List(30,20)
</pre>
</div>
<p>Fixing it didn&#8217;t take much time however, which was a relief because I thought I had completely messed up. I&#8217;ve updated the post with a version which is (hopefully) now correct (so you can see the fix in the frame function and helper functions throws_for_frame_score and throws_in_frame), and also updated the tests into some more sensible ones. The wtf version is still left to its original, fixing that would probably even make it more horrible than its original. Thanks to Ilian for pointing this out, clearly can&#8217;t beat Uncle Bob.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/25/functional-bowling-in-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F25%2Ffunctional-bowling-in-scala%2F&amp;title=Functional%20bowling%20in%20Scala" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/25/functional-bowling-in-scala/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Scala REPL tips and tricks (trunk only)</title>
		<link>http://blog.xebia.com/2009/07/19/scala-repl-tips-and-tricks-trunk-only/</link>
		<comments>http://blog.xebia.com/2009/07/19/scala-repl-tips-and-tricks-trunk-only/#comments</comments>
		<pubDate>Sun, 19 Jul 2009 13:03:12 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[General]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2618</guid>
		<description><![CDATA[The path on the road to learning Scala usually involves using the REPL. this is a very handy way of trying out functions you write easily and quickly, without having to set up an entire IDE environment. Scala&#8217;s latests stable release Scala 2.7.5. Scala 2.8 will be out in a couple of months, as things [...]]]></description>
			<content:encoded><![CDATA[<p>The path on the road to learning Scala usually involves using the REPL. this is a very handy way of trying out functions you write easily and quickly, without having to set up an entire IDE environment. Scala&#8217;s latests stable release Scala 2.7.5. Scala 2.8 will be out in a couple of months, as things stand now. This new release will contain a number of enhancements and new features, and if you can&#8217;t wait to try this out, you should check out and use the trunk. I&#8217;ve previously <a href="http://blog.xebia.com/2009/07/03/starting-out-with-scala/">blogged</a> about starting with Scala, and also hinted at trying this out. In this blog, I&#8217;ll show some more concrete examples of the and a few neat things that you can do if you&#8217;re willing to take this step.<br />
<span id="more-2618"></span></p>
<p><strong>Get the trunk</strong><br />
To use the trunk, you can either check out the sources and build it yourself, our take the <a href="http://www.scala-lang.org/node/212/distributions">nightly builds</a>.  You&#8217;ve probably set a SCALA_HOME environment variable, so just point it to the newly created build and fire up the REPL. If all has gone well, you should see something like the following:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
Welcome to Scala version 2.8.0.r18341-b20090718103640 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_14).
Type in expressions to have them evaluated.
Type :help for more information.
scala>
</pre>
</div>
<p>Using the trunk, the first thing you can profit from is using the redesigned and improved Scala collection library.<br />
It has undergone a large redesign effort, largely done by Martin Odersky himself. It has been checked in and been living in the trunk for a while now, so using the trunk you can have the advantage working with it. The new API is explained in the <a href="http://www.scala-lang.org/sites/default/files/sids/odersky/Sat,%202009-05-30,%2012:51/collections.pdf">Scala Improvement Proposal</a>, an excellent and must read for understanding the design of Scala&#8217;s collections. </p>
<p><strong>Using the revamped REPL</strong><br />
<a href ="http://extempore.livejournal.com/">Paul Phillips</a> not only solves one bug after the other in the trunk, he also has the habit of pimping the REPL on a regular basis.<br />
A very nice feature is that there is code completion, very handy if you don&#8217;t have the complete Scala API in your head. First, define a variable and after typing the variable (and possibly the start of a function) hit tab:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> l
AbstractStringBuilder       Annotation                  Appendable                  Application
Array                       AssertionStatusDirectives   BigDecimal                  BigInt
Boolean                     Byte                        Cell                        CharSequence
Character                   CharacterData00             CharacterData01             CharacterData02
CharacterData0E             CharacterDataLatin1         CharacterDataPrivateUse     CharacterDataUndefined
Class                       ClassLoader                 ClassfileAnnotation         Cloneable
Comparable                  Compiler                    ConditionalSpecialCasing    Console
CountedIterator             Deprecated                  Double                      Either
Enum                        Enumeration                 Equiv                       Float
Fractional                  Function                    GenericRange                Immutable
InheritableThreadLocal      Integer                     Integral                    Iterable
Left                        Long                        Math                        Mutable
None                        NotNull                     Number                      Numeric
Object                      Option                      Ordered                     Ordering
Override                    Package                     PartialFunction             PartialOrdering
PartiallyOrdered            Predef                      Process                     ProcessBuilder
ProcessEnvironment          ProcessImpl                 Product                     Proxy
Range                       RangeToString               Readable                    Responder
Right                       Runnable                    Runtime                     RuntimePermission
ScalaObject                 SecurityManager             SerialVersionUID            Short
Shutdown                    Some                        StackTraceElement           StaticAnnotation
StrictMath                  String                      StringBuffer                StringBuilder
StringCoding                SuppressWarnings            Symbol                      System
SystemClassLoaderAction     Terminator                  Thread                      ThreadDeath
ThreadGroup                 ThreadLocal                 Throwable                   TypeConstraint
UNIXProcess                 Unhashable                  UniquenessCache             Void
actors                      annotation                  ch                          cloneable
collection                  com                         compat                      concurrent
dbc                         deprecated                  inline                      instrument
io                          java                        javax                       jline
l                           management                  mobile                      native
net                         noinline                    org                         package
ref                         reflect                     remote                      runtime
scala                       serializable                settings                    specialized
sun                         sunw                        swing                       testing
text                        throws                      tools                       transient
unchecked                   unsealed                    util                        volatile
xml

scala> l.zip

zip            zipAll         zipWithIndex
</pre>
</div>
<p>Pretty neat. But that&#8217;s not all: the trunk REPL now contains a power user mode:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
scala> :help
All commands can be abbreviated - for example :h or :he instead of :help.

:help prints this help message.
:jar add a jar to the classpath.
:load followed by a filename loads a Scala file.
:power enable power user mode.
:quit exits the interpreter.
:replay resets execution and replays all previous commands.
:silent disable/enable automatic printing of results.

scala> :power
** Power User mode enabled - BEEP BOOP      **
** New vals! Try interpreter.<tab>          **
** New defs! Try mkType("T", "String")      **
** New cmds! :help to discover them         **

:help prints this help message.
:jar add a jar to the classpath.
:load followed by a filename loads a Scala file.
:power enable power user mode.
:quit exits the interpreter.
:replay resets execution and replays all previous commands.
:silent disable/enable automatic printing of results.
:dump displays a view of the interpreter's internal state.
:tree displays ASTs for specified identifiers.
</pre>
</div>
<p>Let&#8217;s try some of this. Using mkType we can define a type alias, just as Haskell:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>scala> mkType("IntList", "List[Int]")
defined type alias IntList
res3: scala.tools.nsc.InterpreterResults.Result = Success

scala> val il: IntList = List("1","2","3")
<console>:5: error: type mismatch;
 found   : java.lang.String("1")
 required: Int
       val il: IntList = List("1","2","3")

scala> val il:IntList = List(1,2,3,4)
il: IntList = List(1, 2, 3, 4)

scala> il.foldLeft(0)(_+_)
res5: Int = 10
</pre>
</div>
<p>Works like a charm. </p>
<p>Next, the :tree command displays some AST for classes and functions you&#8217;ve defined, if you&#8217;re interested in this:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
scala> def sum(a: Int)(b: Int)(c: Int) = a + b + c
sum: (a: Int)(b: Int)(c: Int)Int

scala> :tree sum
def sum(a: Int)(b: Int)(c: Int) = a.$plus(b).$plus(c) (DefDef)
</pre>
</div>
<p>Last but not least, we can make use of Scala&#8217;s new cutting edge features. For instance, Scala has limited support for applying tail call optimizations at compile time. Determining whether the compiler actually will perform this optimization can be a tricky business however. If you&#8217;re using this, but are unsure whether a function that you have written will actually be optimized by the compiler, you can use the @tailrec annotation now. For instance (the example is taken from the Programming in Scala book) the boom function shown below is not tail recursive, because of the increment function at the end. The bang function on the other hand is. </p>
<pre class="brush: scala; title: ; notranslate">
import scala.annotation.tailrec
class Tails {
  @tailrec def boom(x: Int): Int = {
  if (x == 0) throw new Exception(&quot;boom!&quot;)
  else boom(x-1)+ 1
}

  @tailrec def bang(x: Int): Int = {
  if (x == 0) throw new Exception(&quot;bang!&quot;)
  else bang(x-1)
  }
}
</pre>
<p>Using the @tailrec annotation on both, the compiler gives the following error:</p>
<div style="background-color:#eee;font-family: 'lucida console', 'Courier New', monospace;font-size: 10px;display:block;padding:3px;margin:10px 0px;border: 1px solid #d3d3d6;">
<pre>
<console>:8: error: could not optimize @tailrec annotated method
         @tailrec def boom(x: Int): Int = {
                      ^
<console>:13: error: could not optimize @tailrec annotated method
         @tailrec def bang(x: Int): Int = {
</pre>
</div>
<p>A bit confusing at first sight, since we get compilation errors for both methods, while we were pretty sure the bang method should be tail recursive. However, this can be explained by the fact that the bang method is defined in a class as public and not final. This means it could be overridden in a subclass, thereby preventing tail call optimization. Subtleties like this really makes this annotation quite useful. If we change the class into an object (for which methods can&#8217;t be overridden), and remove the @tailrec annotation from the boom method, all compiles fine. </p>
<p>For more tail call and trampolining explorations in Scala, <a href="http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html">Rich Dougherty&#8217;s blog</a> is a good place to start. Also check out the Scala&#8217;s <a href="https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/library/scala/util/control/TailRec.scala">TailRec</a> class, which is available in the trunk, and  <a href="http://www.nabble.com/Tail-calls-via-trampolining-and-an-explicit-instruction-td20702915.html">this thread</a> for discussion of it.</p>
<p>I haven&#8217;t touched all of the new features that will be in Scala 2.8.0, but some a basic overview can be found <a href="http://article.gmane.org/gmane.comp.lang.scala.internals/273">here</a>. Take a look and enjoy.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/19/scala-repl-tips-and-tricks-trunk-only/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F19%2Fscala-repl-tips-and-tricks-trunk-only%2F&amp;title=Scala%20REPL%20tips%20and%20tricks%20%28trunk%20only%29" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/19/scala-repl-tips-and-tricks-trunk-only/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Real world functional programming in Scala &#8211; comparing Java, Clojure and Scala</title>
		<link>http://blog.xebia.com/2009/07/04/real-world-functional-programming-in-scala-comparing-java-clojure-and-scala/</link>
		<comments>http://blog.xebia.com/2009/07/04/real-world-functional-programming-in-scala-comparing-java-clojure-and-scala/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 14:16:00 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[funtional programming]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2412</guid>
		<description><![CDATA[I recently started reading Stuart Halloway&#8217;s book &#8216;Programming in Clojure&#8217;. I don&#8217;t think I will be writing much enterprise applications in that language in the near future, but it never hurts to broaden the mind, and it&#8217;s a very good read. In his book, he demonstrates some of the advantages of functional programming by taking [...]]]></description>
			<content:encoded><![CDATA[<p>I recently started reading Stuart Halloway&#8217;s book &#8216;Programming in Clojure&#8217;. I don&#8217;t think I will be writing much enterprise applications in that language in the near future, but it never hurts to broaden the mind, and it&#8217;s a very good read. In his book, he demonstrates some of the advantages of functional programming by taking an example from the Apache commons library: StringUtils.indexOfAny. He has also written a <a href="http://blog.thinkrelevance.com/2008/12/1/living-lazy-without-variables">blog</a> about it.<br />
In this blog post, we&#8217;ll compare the original function in Java, the Clojure version and a Scala implementation.<br />
<span id="more-2412"></span></p>
<p>To start: here&#8217;s the original implementation in Java:</p>
<pre class="brush: java; title: ; notranslate">
// From Apache Commons Lang, http://commons.apache.org/lang/
public static int indexOfAny(String str, char[] searchChars) {
  if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
      return -1;
  }
  for (int i = 0; i &lt; str.length(); i++) {
      char ch = str.charAt(i);
      for (int j = 0; j &lt; searchChars.length; j++) {
        if (searchChars[j] == ch) {
            return i;
        }
      }
  }
  return -1;
}
</pre>
<p>Sample results of this function are:</p>
<pre class="brush: java; title: ; notranslate">
StringUtils.indexOfAny(null, *)                  = -1
StringUtils.indexOfAny(&quot;&quot; , *)                    = -1
StringUtils.indexOfAny(*, null)                  = -1
StringUtils.indexOfAny(*, [])                    = -1
StringUtils.indexOfAny(&quot;zzabyycdxx&quot; ,['z' ,'a' ]) = 0
StringUtils.indexOfAny(&quot;zzabyycdxx&quot; ,['b' ,'y' ]) = 3
StringUtils.indexOfAny(&quot;aba&quot; , ['z' ])            = -1
</pre>
<p>And now the Clojure code. I&#8217;ve taken the version from the book, (free to download <a href="http://media.pragprog.com/titles/shcloj/flow.pdf">here</a>). The book version defines three functions, instead of the version shown in the blog post.</p>
<hr/>
<pre>
(defn indexed [s] (map vector (iterate inc 0) s))

(defn index-filter [pred coll]
  (when pred
    (for [[idx elt] (indexed coll) :when (pred elt)] idx)))

(defn index-of-any [pred coll]
  (first (index-filter pred coll)))
</pre>
<hr/>
<p>The three functions defined are: </p>
<ol>
<li> indexed returns a sequence of pairs, the first element being the index, the sequence the element. </li>
<li>index-filter returns a sequence of the indexes of matching predicates in the collection. For example, the function call (index-filter #{\a \b} &#8220;abcdbbb&#8221;) yields (0 1 4 5 6)</li>
<li>index-of-any is the StringUtils function. This is now a simple function, just returning the first result of the index-filter function.</li>
</ol>
<p>As Stuart has mentioned in his book, the Clojure version is shorter, less complex, and also more general than the Java version. No special case handling, such as null or empty search character checking. This all just works naturally in the functional version. It can also be easily extended for other functions than just indexOfAny<br />
Since I&#8217;ve been implementing all kinds of nice, but useless little functions in Scala recently, I thought it might be a good idea to try out a more useful example. So let&#8217;s see how well we can do with Scala in implementing this in a similar way as the Clojure version.<br />
Almost immediately, we hit on the dreaded null problem. Scala is not a pure functional language, and you have to beware that parameters that are passed on can be null. You could specify the input arguments as Options, of course, but than the caller of the function still needs to construct either the Some or None value, and to do that the caller would have to check for it being null or not.<br />
So, after spending some time grumbling about this issue, I decided to admit defeat and do the null check. 1-0 for Clojure.</p>
<p>Without further ado, here are the three functions implemented in Scala (N.B. I&#8217;ve used the trunk here, in case you might want to try this out yourself, I haven&#8217;t tried whether this also works version 2.7.5):</p>
<pre class="brush: scala; title: ; notranslate">
def indexed(coll:Seq[Any]):Seq[Pair[Int,Any]] = {
  if (coll==null) List()
  (0 until coll.length).zip(coll)
  //below an alternative, but here we have to traverse the list another time to reverse the elements...
  //coll.zipWithIndex.map(p =&gt; p.swap)
}

def indexedFilter(pred:Seq[Any], coll:Seq[Any]):Seq[Int] = {
  if (pred==null)List()
  val idxList = indexed(coll)
  for (p &lt;- pred; idxPair &lt;- idxList; if (p == idxPair._2)) yield (idxPair._1)
}

def indexOfAny(pred:Seq[Any], coll:Seq[Any]):Option[Int] = {
  val res=indexedFilter(pred, coll)
  if (res.isEmpty) None
  else Some(res.first)
}
</pre>
<p>Following the definition of the indexed function is a no-brainer: Scala&#8217;s zip function on the List class does the job here. There&#8217;s also zipWithIndex which does almost what we want, this returns a List of tuples, but in reverse order as the Clojure sample: element first, index later.<br />
The indexedFilter uses a <a href="http://www.scala-lang.org/node/111">for-comprehension</a> just as the Clojure example (Clojure&#8217;s for is not a traditional loop, but a sequence comprehension). For each element in our predicate sequence it checks whether it is present in the indexed tuples that is the result of the indexed function. If it is, it is added to the resulting list using yield. indexOfAny then becomes a trivial function that just checks whether the resulting sequence is empty or not. Instead of returning -1 if nothing is found, I&#8217;ve used Scala&#8217;s <a href="http://www.scala-lang.org/docu/files/api/scala/Option.html">Option</a> class in this case to make the result more expressive. </p>
<p>The function at least works as expected:</p>
<p><code><br />
scala> indexOfAny("ab", "cdef")<br />
res3: Option[Int] = None<br />
scala> indexOfAny("ab", "bcdefbbb")<br />
res3: Option[Int] = None<br />
scala> indexOfAny("fb", "bcdefbbb")<br />
res4: Option[Int] = Some(4)<br />
</code></p>
<p><strong>Conclusion</strong><br />
All in all, the scala version is not that bad. Its main drawback over the Clojure version is the two null checks that we need to do, and also we need to check the resulting list being empty or not in the indexOfAny function. Clojure wins in this respect. However, the Scala version still is pretty neat and generic and improves (in my opinion at least) the original Java version. </p>
<p><strong>Update: handling infinite collections</strong><br />
Stuart asked the question in his comment how the Scala version would handle infinite collections. The version presented above does not handle this very well. For instance, you&#8217;ll get a OEM if you try to pass on Stream.from(0) (which constructs a lazy infinite list of all natural numbers) to the indexed function. Also the indexedFilter function evaluates the entire collection, which is strictly not necessary for the indexOfAny function. To handle an infinite collection, we need to modify and optimize the functions somewhat, to resemble a bit more the functions that Stuart has used in his blog post, instead of the book versions. The Clojure functions used in the blog post look like this:</p>
<hr/>
<pre>
(defn indexed [s] (map vector (iterate inc 0) s))

(defn index-of-any [s chars]
  (some (fn [[idx char]] (if (get chars char) idx))
          (indexed s)))
</pre>
<hr/>
<p>The Scala version that I came up with is as follows:</p>
<pre class="brush: scala; title: ; notranslate">
def lazyIndexed(coll:Seq[Any]):Seq[Pair[Int,Any]] = {
  if (coll==null) Stream.empty
  Stream.from(0).zip(coll)
}

def lazyIndexOfAny(pred:Seq[Any], coll:Seq[Any]):Option[Int] = {
  if (pred==null) None
  lazyIndexed(coll).dropWhile(ip =&gt; !pred.exists(p =&gt; (p == ip._2))).headOption.map(ip =&gt; ip._1)
}
</pre>
<p>As said, Scala&#8217;s <a href="http://www.scala-lang.org/docu/files/api/scala/Stream.html">Stream</a> implements a lazy list, in which the elements are only evaluated when needed. In this case, we keep on drop elements from it list that do not appear in the predicate sequence. The head of the remaining list is the first matching result. </p>
<p>Obvious drawback here is that this indeed does works on infinite collections, but only if a match can be found, else we&#8217;re still in trouble.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/04/real-world-functional-programming-in-scala-comparing-java-clojure-and-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F04%2Freal-world-functional-programming-in-scala-comparing-java-clojure-and-scala%2F&amp;title=Real%20world%20functional%20programming%20in%20Scala%20%26%238211%3B%20comparing%20Java%2C%20Clojure%20and%20Scala" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/04/real-world-functional-programming-in-scala-comparing-java-clojure-and-scala/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Starting out with Scala</title>
		<link>http://blog.xebia.com/2009/07/03/starting-out-with-scala/</link>
		<comments>http://blog.xebia.com/2009/07/03/starting-out-with-scala/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 11:07:23 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2342</guid>
		<description><![CDATA[Scala has become more and more popular over the recent months/years. Its hybrid nature of being an imperative as well as functional language attracts a crowd from the Java world as well as functional fundamentalists coming from the world where statements like x=x+1 are looked at with the utter disbelief. It has been stated that [...]]]></description>
			<content:encoded><![CDATA[<p>Scala has become more and more popular over the recent months/years. Its hybrid nature of being an imperative as well as functional language attracts a crowd from the Java world as well as functional fundamentalists coming from the world where statements like x=x+1 are looked at with the utter disbelief. It has been stated that Scala is &#8216;Java as it should have been&#8217;, but there are also numerous complaints about the language and its features (like not being side effect free, overly complex, too much of everything, too much abstraction, having a weird syntax, etc). The latter might actually be a proof of its popularity, since people seem to be actually using the language instead of just looking at it briefly and stopping, tired but happy, after having written hello world with it.<br />
In this blog post, I&#8217;ll give you some (hopefully) useful tips how to best start if you want to learn this language, which is one of the candidates become &#8216;our next big language&#8217; and surpass Java in this respect.<br />
<span id="more-2342"></span></p>
<p><strong>Pick an IDE, or not</strong><br />
The first problem you might encounter is that the various Scala IDE plugins have not yet reached the maturity of the Java support that you might have been accustomed to. Lots of hard work is in progress on this, but you still might experience hickups and freezes (as I have) of your favorite IDE. At this moment, the Netbeans plugin seems to be the most stable (this is the IDE that David Pollak, creator of Lift, seems to use). If you&#8217;re an eclipse user, you&#8217;ll probably want the nightly build version of the Scala plugin, since that&#8217;s the only one actively under development. This means that you need the Scala trunk to work with, however.</p>
<p>There&#8217;s also plenty of support for non-IDE&#8217;s, and recently I&#8217;ve tried switching back to emacs again. For some, this brings back memories to good old university days, others may find it the utmost horror. I must say, I found it to be a rather soothing experience after years of development using Eclipse. You&#8217;ll need to do some setup work to get a good Scala experience. An excellent blog post describing how to setup your emacs environment for Scala using Yasnippet, exuberant ctags and maven can be found <a href=" http://thegreylensmansview.blogspot.com/2009/02/stone-tools-and-scala-development-part.html">here</a>.</p>
<p><strong>Try out the trunk</strong><br />
The latest released version of Scala is 2.7.5. The next version will be 2.8.0, but its release date is still not known. However, the invaluable Paul Philips has done many bug fixes and improvements in the Scala compiler and the REPL, all hanging out in the trunk. To take full advantage of this, check out the sources and build them. Note that the Scala collections API has been redesigned in the trunk, and differs from the 2.7.5 release. To get a good understanding of the new design, and the API in general, you&#8217;re encouraged to read the new collection SIP (Scala improvement proposal) <a href="http://www.scala-lang.org/sites/default/files/sids/odersky/Sat,%202009-05-30,%2012:51/collections.pdf">available here</a>.</p>
<p><strong>Read a book</strong><br />
The standard work is Programming in Scala, co-authored by Martin Odersky (creator of Scala) himself. This book is lengthy but very thorough, providing plenty of examples. Another book that has seen the light is Beginning Scala by David Pollak (already mentioned). I have not read this, but reviews suggest this is also an excellent start. More books will hit the market this year. </p>
<p><strong>Check out Lift</strong><br />
Eventually it is possible that you might start to really like Scala and want to use it in the enterprise. <a href="http://liftweb.net/">Lift</a> is the first web framework written in Scala, created by <a href="http://blog.lostlake.org">David Pollak</a>. Downloading and creating a simple web application to work is a no-brainer. The distribution comes with plenty of maven archetypes to get a basic web application ready in under than five minutes. Lift has its own database mapping framework, but there&#8217;s JPA support as well, if you like this. JTA integration is also being worked on.</p>
<p><strong>Read some articles</strong><br />
There are loads of (both academic and slightly less academic) articles about Scala. For example, if you want to know the rationale behind Scala&#8217;s actor library design, read the scala  <a href="http://lamp.epfl.ch/~phaller/actors.html">actor papers</a>.<br />
Martin Odersky&#8217;s homepage also contains a long list of <a href="http://lampwww.epfl.ch/~odersky">his publications</a>.<br />
It provides lots of material to provide insight in the design of Scala and its libraries. If you&#8217;re not that academically inclined and from a Java background, try <a href="http://www.ibm.com/developerworks/java/library/j-scala01228.html">The busy java developer&#8217;s guide to Scala</a>, by Ted Neward. Provides a nice introduction.</p>
<p><strong>Read some blogs.</strong><br />
Plenty of blogs available, here are some I like:</p>
<ul>
<li><a href="http://www.codecommit.com/blog/scala/">Daniel Spiewak</a> Lots of useful Scala examples.</li>
<li><a href="http://dibblego.wordpress.com">Tony morris</a>. He&#8217;s the creator of <a href="http://functionaljava.org/">functional java</a> and of <a href="http://code.google.com/p/scalaz/">Scalaz</a>. Beware however, if you check this out you might end up in deep functional waters where Monads reign.</li>
<li><a href="http://jonasboner.com">Jonas Boner</a>He has lots of experience of using Scala in the real world, some of which he has blogged extensively about. Well worth the read.</li>
<li><a href="http://www.planetscala.com">Planet Scala</a> Perhaps you don&#8217;t even need more than this. This aggregates numerous blog posts (including the one mentioned above) about Scala.
</ul>
<p><strong>Join IRC</strong><br />
Scala has an IRC channel, which can be found <a href="irc://irc.freenode.net/scala">here</a>. Whenever you&#8217;re stuck at some problem you&#8217;re working at, there&#8217;s always the mailing lists, but many knowledgeable people hang out on a daily basis on the IRC channel. Use <a href="http://paste.pocoo.org/">lodgeit</a> to show the code you&#8217;re stuck with, and you&#8217;ll get an answer in no time. </p>
<p><strong>Start coding.</strong><br />
Lift might be the choice if you really want to write some useful, practical real world web applications. If you&#8217;re totally impractical like me, pick a few problems from <a href="http://projecteuler.net/">project euler</a>, or the 99 problems projects (solutions in Scala can be found <a href="http://aperiodic.net/phil/scala/s-99">here</a>. Many excellent programmers have taken this path, it&#8217;s fun and an excellent way to play around with the core Scala API. </p>
<p>To put into practice what I preach here, a few lines of Scala code to either whet your appetite or make you run away screaming. Note that my Scala knowledge is still in the pre-kindergarten stage, I&#8217;m barely able to speak, so laugh at will when viewing this code. </p>
<p>First, a randomly picked Euler problem, <a href="http://projecteuler.net/index.php?section=problems&#038;id=48">number 48</a>, just because I like onliners:</p>
<pre class="brush: scala; title: ; notranslate">
(1 to 1000).map(x =&gt; new java.math.BigDecimal(x).pow(x)).reduceLeft((a,b) =&gt; a.add(b)).remainder(new java.math.BigDecimal(10).pow(10))
</pre>
<p>This one liner is not nearly as concise and neat as the Haskell version, but it will do. If nothing else, it has at least has the tiny merit of showing Scala &#8211; Java interoperability. </p>
<p>Another randomly picked and slightly more complex one, problem <a href="http://projecteuler.net/index.php?section=problems&#038;id=21">number 21</a>:</p>
<pre class="brush: scala; title: ; notranslate">
object Euler21 {
  def sumOfDivisors(number: Int): Int = {
    List.range(1, number).filter{i =&gt; (number % i) == 0}.foldLeft(0){(a,b) =&gt; a+b}
  }

  def solver(): Int  = {
      (for (i &lt;- 0 until 10000; di = sumOfDivisors(i); if(di &gt; i &amp;&amp; sumOfDivisors(di)  == i) ) yield (i+di)).foldLeft(0){(a,b) =&gt; a+b};
  }
}
</pre>
<p>Enjoy.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/03/starting-out-with-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F03%2Fstarting-out-with-scala%2F&amp;title=Starting%20out%20with%20Scala" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/03/starting-out-with-scala/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Accessing generic types at runtime in Java</title>
		<link>http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/</link>
		<comments>http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/#comments</comments>
		<pubDate>Sat, 07 Feb 2009 09:50:32 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[JPA]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=886</guid>
		<description><![CDATA[I was writing my n-th Dao implementation, this time using JPA. I (and probably a whole lot of others) usually create a DAO per entity, parameterizing the entity type. Specific DAO instances for entities implement the generic DAO using their entity type as type parameter. One generic DAO implementation exists, containing common operations like findById, [...]]]></description>
			<content:encoded><![CDATA[<p>I was writing my n-th Dao implementation, this time using JPA.<br />
I (and probably a whole lot of others) usually create a DAO per entity, parameterizing the entity type.<br />
Specific DAO instances for entities implement the generic DAO using their entity type as type parameter. One generic DAO implementation exists, containing common operations like findById, persist, remove, etc. This generic DAO uses the class type specified by the implementing DAO classes (e.g. a Person) to manipulate or query the entity specified by this type. The (slightly) annoying problem for me has always been to instantiate that entity type in the generic DAO superclass. I&#8217;ve always done this by just creating a constructor in the generic DAO which takes a class argument  containing the required Class of the entity. However, there&#8217;s a better way, which I&#8217;ll show in this post.<br />
<span id="more-886"></span></p>
<p>To start with an example, the generic DAO interface looks like this:</p>
<pre lang="java">
public interface GenericEntityDao<T> {

   T findById(Serializable id);

   List<T> findAll();

   ... more methods omitted
}
</pre>
<p>And its generic DAO implementation class looks something like this:</p>
<pre lang="java">
public abstract class GenericJpaDao<T> implements GenericDao<T> {

  private Class<T> entityBeanType;

  @PersistenceContext
  private EntityManager entityManager;

  public T findById(Serializable id) {
     return entityManager.find(getEntityBeanType(), id);
  }

  public List<T> findAll() {
      return entityManager.createQuery("from " + getEntityBeanType().getName() )
                          .getResultList();
  }

  protected Class<T> getEntityBeanType() {
      return entityBeanType;
  }
  ... more methods omitted

}
</pre>
<p>The question is, how do we obtain the parametized type of T for the entityBeanType field to use in our queries? Earlier, I used to just instantiate this type in the constructor, like so:</p>
<pre lang="java">
public GenericJpaDao(Class<T> entityBeanType) {
     this.entityBeanType = entityBeanType;
}

public JpaPersonDao extends GenericJpaEntityDao<Person> implements PersonDao {
   public PersonDao() {
      super(Person.class);
   }
}
</pre>
<p>But this is a bit silly, since we already know from the type parameter <Person> that the entity we&#8217;re interested in has type Person.<br />
However, there is an easier way out: we can use Java&#8217;s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html">ParameterizedType</a> class to obtain information about the declared generic type. As stated in the javadoc:</p>
<blockquote><p>
 /**<br />
 * ParameterizedType represents a parameterized type such as<br />
 * Collection&lt;String&gt;.<br />
 *<br />
 * A parameterized type is created the first time it is needed by a<br />
 * reflective method, as specified in this package. When a<br />
 * parameterized type p is created, the generic type declaration that<br />
 * p instantiates is resolved, and all type arguments of p are created<br />
 * recursively.
</p></blockquote>
<p><br/>
<p/>
Thus, it seems that ParameterizedType contains the information that we want. How do we obtain an instance of it? The answer lies in Java&#8217;s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getGenericSuperclass()">getGenericSuperclass</a> method, defined on the Class object. This returns a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Type.html">Type</a> representing the superclass of this Class. The Javadoc of the method states the following:</p>
<blockquote><p>
     * If the superclass is a parameterized type, the <tt>Type</tt><br />
     * object returned must accurately reflect the actual type<br />
     * parameters used in the source code. The parameterized type<br />
     * representing the superclass is created if it had not been<br />
     * created before.
</p></blockquote>
<p><br/><br />
The Type interface itself is just a marker interface, containing no methods. Depending on the case at hand, an Type extending the Type interface will be returned. In our case, we&#8217;ll use the getGenericSuperclass method on a class extending our GenericJpaDao class. Thus, the superclass is JpaGenericDao, which is a parameterized type. In this case, the actual the Type object returned by getGenericSuperClass will be a ParameterizedType instance. This class contains a method <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments()">getActualTypeArguments</a>, which returns an array containing all generic type parameters used in the source code. </p>
<p>This is precisely what we desire, so in our GenericJpaDao class constructor, can get rid of the Class argument, and instead do the following:</p>
<pre lang="java">
  @SuppressWarnings("unchecked")
  public GenericJpaDao() {
    this.entityBeanType = ((Class<T>) ((ParameterizedType) getClass()
        .getGenericSuperclass()).getActualTypeArguments()[0]);
  }
</pre>
<p>We know there&#8217;s precisely one type argument in our class, so we can take the first element of the array that is returned, which provides the Class of our entity. Thus we can get rid of all the annoying constructors with Class arguments, and handle determination of the entity type in just one place.</p>
<p>This may not provide the highest amount of code reduction you have ever experienced, but it&#8217;s a neat trick in any case.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F02%2F07%2Facessing-generic-types-at-runtime-in-java%2F&amp;title=Accessing%20generic%20types%20at%20runtime%20in%20Java" id="wpa2a_12"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>QCON SF: return of the fundamentalist functional programmer</title>
		<link>http://blog.xebia.com/2008/11/30/qcon-sf-return-of-the-fundamentalist-functional-programmer/</link>
		<comments>http://blog.xebia.com/2008/11/30/qcon-sf-return-of-the-fundamentalist-functional-programmer/#comments</comments>
		<pubDate>Sun, 30 Nov 2008 12:00:00 +0000</pubDate>
		<dc:creator>Arjan Blokzijl</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[qcon]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=831</guid>
		<description><![CDATA[While attending QCon San Francisco, I had the particular pleasure of attending a whole track that was devoted to the area of functional programming, a topic that I have a profound interest in. After having followed the track, I&#8217;m even more convinced than before that functional programming is not confined the the academic world. I [...]]]></description>
			<content:encoded><![CDATA[<p>While attending <a href="http://qconsf.com/">QCon San Francisco</a>, I had the particular pleasure of attending a whole track that was devoted to the area of functional programming, a topic that I have a profound interest in. After having followed the track, I&#8217;m even more convinced than before that functional programming is not confined the the academic world. I think that it will have a profound impact on our mental perspective and the way we think about programming and problem solving in the next coming years. In this blog, I will summarize the sessions I followed, provide you with a couple of thought provoking ideas that I picked up, and hopefully makes you think about your programming style.</p>
<p><span id="more-831"></span></p>
<p>The track started of with what seemed like a rather unusual combination: a presentation by <a href="http://cs-www.cs.yale.edu/homes/hudak-paul/">Paul Hudak</a> about <a href="http://www.haskell.org/">Haskell</a> and the Arts.<br />
He talked about the concept of <a href="http://www.haskell.org/haskellwiki/Functional_Reactive_Programming">Functional Reactive Programming</a>  (FRP), now a key area of research at the University of Yale. FRP is a programming style where each function can capture a time varying quantity (for instance input sound, video, user actions). This style of programming has applications in Robotics, parallel programming, audio processing. Whenever a new input value is given to a function, it is re-evaluated and new output is returned. In his talk, he presented specially HasCore and HasSound, domain specific languages developed for music and sound synthesis. Paul said that functional languages are specially suited for computer music, as they are declarative (saying &#8216;What&#8217; should be done, instead of &#8216;How&#8217; it should be done). Haskells abstraction mechanisms allow for musical programs that are elegant, precise and powerful, using the mechanisms of lazy evaluation, higher order functions, algebraic data types and type classes. A basic example of music modeling in Haskell can be found <a href="http://www.haskell.org/haskore/onlinetutorial/basics.html"/>here</a>. </p>
<p>The next talk was given by Lennart Augustsson on a very different subject, yet no less interesting: implementing Domain Specific Languages in Haskell. It seams that, whenever the topic of DSL&#8217;s is mentioned to a Haskell programmer, a wry smile will appear on his face, since this has been done since ages in Haskell already, and it&#8217;s hard for him to see why it&#8217;s currently such a hype.<br />
Lennart gave a couple of examples which he himself had developed by implementing DSL&#8217;s in Haskell. For me, the most striking was the case where he had implemented a DSL for generating Excel (i.e. the real Excel sheets, not just a text based csv file). As he stated, Excel has a somewhat rudimentary abstraction mechanism, consisting only of copy and past re-use. However it is used widely by business people and is a familiar UI. Therefore, the solution is to generate Excel sheets. Lennart is an advocate of strong type checking to prevent errors at compile time. He showed how he had used Haskells type classes, and also a more obscure concept as <a href="http://www.haskell.org/haskellwiki/Phantom_type">Phantom types</a> in his Excel DSL. The result was a DSL capable of generating Excel sheets without allowing type errors in operations, such as the addition of two cells in Excel where one contains an integer and the other containing a string, a thing that Excel itself does not prevent. An interesting and also amusing session indeed, showing the full power of Haskells type system capabilities, and demonstrating a use of it in an area that probably does not spring directly to the mind when thinking of Haskell.</p>
<p>A perhaps more familiar concept to most of us was demonstrated in a session given by David Pollak . He talked about a web application, <a href="http://buyafeature.com/">Buy a feature</a>, that he had developed recently. A subject that perhaps will not raise most interest immediately, however, David had used <a href="http://www.scala-lang.org/">Scala</a> and Scala&#8217;s <a href="http://liftweb.net/index.php/Main_Page">Lift</a> web framework, the latter being created by himself. He had been using functional programming paradigms, including Scala&#8217;s Actor library to deal with concurrency, in order to implement a multi-user, web-based, real-time, serious game. As he stated, the team initially used the Java&#8217;s imperative programming style. However, after some time (and coaching) they gradually move over to use the declarative, functional programming style that Scala also offers. Some more noteworthy statements were, that none of the bugs found in the application were concurrency related, apparently the event driven, message passing programming style using Scala&#8217;s Actor library served him well.<br />
Also, he stated, the amount of unit tests he needed to comfortably put this system into production had been considerably less (in the order of 30% if my remember correctly) compared to the amount of test coverage required when using Ruby and Rails, which he has also been using extensively. An interesting case study, and one of the first real world examples about Scala&#8217;s usage that I had heard of. If you&#8217;re interested, read David&#8217;s <a href="http://blog.lostlake.org/index.php?/archives/73-For-all-you-know,-its-just-another-Java-library.html#extended">blog</a>) for more on this topic.</p>
<p>The day&#8217;s ending could not have been much better for a functional programming adherent.<br />
Eric Meijer himself concluded it, with a delightful talk titled &#8216;The fundamentalist functionalist programming&#8217;.  His thought provoking argument is that we&#8217;ve been moving into the wrong directions for the last dozens of years in the way we program, and it&#8217;s time to see change direction. Turning, as the title of this blog indicates, to pure, fundamental functional programming.<br />
Why would this be a good thing? All &#8216;pure&#8217; functional code has no side effects, and therefore does not alter state. Lacking state that is altered, the order in which statements are executed does not matter, nor does number of times a program gets executed. This makes programs better understandable and far less error prone. How nasty an implicit side effect of a function can be was shown by Eric with an example from the C# language. It would make this blog too lengthy to go into detail, so for the interested reader should take a look at his <a href="http://research.microsoft.com/~emeijer/Blog/LookClosure.html">blog</a>.</p>
<p>Now, many will think along these lines: &#8216;no side effects, thus, no use&#8217;, specially when thinking about how to do IO, which always causes some side effect. Actually Eric&#8217;s main argument about fundamentalist functional programming was not that all side effects are bad. Indeed he argued that any program can have side effects, and that side effects are even a good thing. However, his main argument was that all side effects should be made explicit in the language. It&#8217;s the implicit side effects hidden in function or method calls that leads to surprising and unexpected results and as a consequence lengthy debugging sessions. Even <a href="http://www.erlang.org/">Erlang</a> is not a &#8216;pure&#8217; functional language in the fundamentalist sense, since IO operations as well as the spawning of a new process do have side effects that are implicit in the language.<br />
The language Eric has taken part in designing, Haskell, is naturally the language he is advocating to use, and if not the language itself, then at least its ideas. In Haskell, all side effects are coded in <a href="http://www.haskell.org/all_about_monads/html/index.html">Monadic</a> classes. Eric gave a simple example about this concept, stating that a Monad can be simply be understood as a Collection of values of things that change. He made the comparison of a watch being a Monad, of which the time has a different value each time you take a look at it. The watch does not change itself, but the value it represents does. Monadic classed can be passed around functions without letting side effects escape the Monadic class itself. By using this mechanism, it is immediately obvious which parts of a program actually do change state, and this makes programs easier to understand.<br />
One might think that these concepts are still only of academic interest. However, as Eric showed, it&#8217;s already out there in <a href="http://msdn.microsoft.com/en-us/vbasic/aa904594.aspx">LINQ</a>, .NET&#8217;s language-integrated query, set, which uses Monadic classes and lazy evaluation. So if you if you&#8217;re a C# programmer, you&#8217;re already dealing with these functional concepts. C# incorporates more and more functional features into the language. </p>
<p>A very thought provoking talk that made me think why the whole world is not using a functional programming style. However, after this day, I&#8217;m convinced that functional programming is very much alive, and we&#8217;ll see an increasing use of it and its ideas in our daily work. I think we need to embrace those ideas to take full advantage of them in our problem solving and, ultimately, to write better programs.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/11/30/qcon-sf-return-of-the-fundamentalist-functional-programmer/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F11%2F30%2Fqcon-sf-return-of-the-fundamentalist-functional-programmer%2F&amp;title=QCON%20SF%3A%20return%20of%20the%20fundamentalist%20functional%20programmer" id="wpa2a_14"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/11/30/qcon-sf-return-of-the-fundamentalist-functional-programmer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/author/ablokzijl/feed/ ) in 0.89925 seconds, on Feb 9th, 2012 at 4:29 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 5:29 pm UTC -->
