February 18, 2011

Abseiling for ECHO

Well, I think I've finally gone mad :)

Despite the fact that I'm more than a little scared of heights, I shall be abseiling off Guy's Tower (at 469ft the tallest hospital in the world!) on May 2nd. It's in aid of ECHO (Evelina Children's Heart Organisation) who have been such a great support to us given my daughter, Sophie's, heart condition.


So wish me luck, and if you'd like to support ECHO by sponsoring me then you can do so here.

November 02, 2010

Yay! Got to Level 1 on Project Euler

As you may have guessed from the title, I've been hacking away at problems on Project Euler, and in fact have now managed to complete the first 25.

Much of my recent "acceleration" seems to have come from using Scala, as with these "one-off" coding exercises it's very helpful to have powerful functional constructs available when it makes sense to use them, but also to be able to fall back on a "normal" imperative style when it's more convenient.

Which will be first, though... reaching Level 2 or coming up with some "proper" code in Scala to really get a feel for how good it is?

October 14, 2010

Dependency injection in Scala

Here are a few thoughts and code snippets from my admittedly brief experiments with dependency injection in Scala. Comments most welcome, as always!

Option 0: Use your favourite Java framework

I only know Guice, but I imagine the pros and cons are pretty much the same for any other framework. Porting Java annotations to Scala takes some getting used to, and occasionally it's a bit tricky to get right. And, of course, and it might not quite feel like Scala, but at least you'll know the framework and any quirks it may have.

Plenty of tutorials exist already for this option, so I'm sure your favourite search engine can help you find some. Any links I post here are sure to become stale pretty quickly given the rate at which Scala is developing.

Option 1: Just use implicits

Scala implicit parameters can easily cope with simple cases of DI, and have the added advantage that the code is somewhat more idiomatic Scala than would generally result from Option 0. For example, try pasting the following into an interactive Scala session:

trait Logger {
  def log(msg: String)
}

object StdOutLogger extends Logger {
  override def log(msg: String) { println(msg) }
}

object Config {
  implicit def provideLogger = StdOutLogger
}

import Config._

def logTest(msg: String)(implicit logger: Logger) {
  logger.log(msg)
}

logTest("Hello world")

One thing to note is that implicits operate at the function level, whereas DI is normally at the object level (via either constructors or setters). The former can easily be achieved via implicit parameters to an class's constructor, though. Following on from the code above:

class Test(implicit private val logger: Logger) {
  def doSomething {
    logger.log("Doing something...")
  }
}

(new Test).doSomething

Option 2: Adding annotations to implicits

The approach above works fine when you're injecting fairly specific, single-purpose objects. But what if you wanted to inject a string or an integer. Typically DI frameworks use some form of annotation in these circumstances, so let's see if we can come up with a version for Scala implicits (again this should work if pasted into a Scala REPL): 

class Annotated[A, T](private val t: T) {
  def value = t
}

object DeepBlue {
  def answer(implicit annotated: Annotated[DeepBlue.type, Int]) {
    println(annotated.value)
  }
}

object Config {
  implicit def provideAnswer = new Annotated[DeepBlue.type, Int](42)
}

import Config._

DeepBlue.answer

Note that the example above, and the Annotated class in particular, is the simplest possible thing I could come up with that would work, and could likely be improved upon in several ways:

1. I used the (generated) class of the DeepBlue singleton object just because it was handy. Often you'd want to use a class or singleton object created specifically for the purpose. It might even be possible to use case classes or even enumerations to good effect here.

2. It doesn't do anything clever with the annotating type (A). One or more factory methods in a companion object which restrict their arguments a bit more (and maybe the addition of an Annotation trait to help with this) might lead to some nice type inferencing possibilities, especially with singleton objects as in the example. For instance, it would be nice to be able to write the RHS of the provider method as simply Annotated(DeepBlue, 42).

3. I might also be possible to mark the value method as implicit, and have the injection site implicitly convert from an Annotated[A, T] to a T when required. This might be one step too far, though, and just plain confusing rather than helpful (quite a common theme with implicits, unfortunately).

Option 3: For more functionality, implicitly pass an injector

If you need more advanced DI functionality then you may well hit the (somewhat ironic) restriction that all implicit functions (i.e. those that provide the values for implicit parameters) must be explicitly coded, i.e. there's no way (that I know of at least) to programmatically influence the resolution of implicit parameters. I've not spent too much time on this, but the obvious (to me, with my own unique set of influences/biases) way around this would be to build a Guice-like Binding/Module/Injector framework, and then implicitly pass the injector to functions which need injected instances of objects. It may even be possible to use Scala's flexible syntax to create a nice DSL for specifying the bindings. As a warning, though, I have not tried this (yet!) and I suspect it may involve quite a bit of reinventing the wheel, so at this point it may well be worth reverting to Option 0, and using an existing framework.

I hope this was useful, and happy coding!

May 18, 2010

ScribeFire for Chrome now "official"

Announcement here - and I'm writing this post using it :)

Now I've got even less excuse not to post more frequently, except maybe that I've also just discovered how addictive StackOverflow is.

March 31, 2010

It might not be the test that's flaky

I have a feeling this was glaringly obvious to everyone but me, but late last week I had a bit of an "a-ha" moment.

When we say "flaky test" we imply that the test itself, or the test environment, is somehow at fault. Although this may often be the case, it's just possible that the test itself is perfectly sound and the implementation is flaky.

Nothing earth shattering, but I just thought I'd mention it...

March 24, 2010

Kojo - Scala for Kids

Via: www.scala-lang.org:
Kids love computers and many would love to learn how to program them too. Lalit Pant, volunteer Math teacher at Himjyoti School for under-privileged girls in Dehradun, developed Kojo in his 'free' time. Kojo is a very polished, easy to install, cool IDE in which children, (or even grown ups) can learn to program using Scala. Lots of examples, a turtle to drive, good documentation and interactive geometry for those budding mathematicians. If you have kids then Kojo could be a fun experience to share with them. On the other hand if you have some 'free' time Lalit would welcome help to develop Kojo, an Open Source project, further.
Just in time for the Easter holidays :)

March 17, 2010

Using abstract type fields instead of parameterised types in Scala

I've been continuing my exploration of Scala by writing some code to do multi-dimensional measure calculations (something with which I'm quite familiar after about 5 years of doing it "as a day job" in the past, but which I've never been quite happy with a representation for). This can be found at http://code.google.com/p/lascala if you're interested, and any comments (especially on making it more idiomatic in its use of the language) would be much appreciated.

However, the main point of the post was to note that I've found, a little to my surprise, that when building type hierarchies using abstract type fields is often cleaner (less verbose, more DRY) than using parameterised types. When I first saw them mentioned I was sceptical about their usefulness, as I couldn't see why I'd prefer:

trait Base {
  type T
  ...
}

trait Super extends Base {
  type T = String
  ...
}

to:

trait Base[T] {
  ...
}

trait Super extends Base[String] {
  ...
}

And while in such a simple case there is no particular reason to, when building more complex hierarchies it can in fact save some repitition. For example:

trait Measure {
  type K
  type V
  def aggData: Iterable[(K, V)]
}

trait Measure1[U, T1] extends Measure {
  type V = U
  type D1 = T1
  type K = T1
}

trait Measure2[U, T1, T2] extends Measure {
  type V = U
  type D1 = T1
  type D2 = T2
  type K = (D1, D2)
}

trait PreAggregated extends Measure {
  def data: Iterable[(K, V)]
  def aggData = data
}

object ExampleMeasure1 extends Measure1[Int, String] with PreAggregated {
  data = ...
}

object ExampleMeasure2 extends Measure2[Int, String, String] with PreAggregated {
  data = ...
}

This is already appreciably less verbose than the following, especially in the use of the classes which is arguably more important than in their definitions:

trait Measure[K, V] {
  def aggData: Iterable[(K, V)]
}

trait Measure1[V, D1] extends Measure[D1, K]

trait Measure2[V, D1, D2] extends Measure[(D1, D2), K]

trait PreAggregated[K, V] extends Measure[K, V] {
  def data: Iterable[(K, V)]
  def aggData = data
}

object ExampleMeasure1 extends Measure1[Int, String] with PreAggregated[String, Int] {
  data = ...
}

object ExampleMeasure2 extends Measure2[Int, String, String] with PreAggregated[(String, String), Int] {
  data = ...
}

Some of the duplication could be avoided by having a series of PreAggregated traits mirroring the dimensional MeasureN ones, but this can get bloated very quickly, especially as it's likely that I'll need to support at least six dimensions. And repition also reappears when traits are stacked (e.g. to encapsulate storage and caching behaviours):

trait Measure[K, V] {
  def aggData:Iterable[(K, V)]
}

trait Measure1[V, D1] extends Measure[D1, K]

trait Measure2[V, D1, D2] extends Measure[(D1, D2), K]

trait PreAggregatedMeasure1[V, D1] extends Measure1[V, D1] {
  def data: Iterable[(D1, V)]
  def aggData = data
}

trait PreAggregatedMeasure2[V, D1, D2] extends Measure2[V, D1, D2] {
  def data: Iterable[((D1, D2), V)]
  def aggData = data
}

object ExampleMeasure1 extends PreAggregatedMeasure1[Int, String] {
  data = ...
}

object ExampleMeasure2 extends PreAggregatedMeasure2[Int, String, String] {
  data = ...
}

Comments?

February 27, 2010

Handy iGoogle gadget for good habit forming

I recently found the Days Since gadget, which seems to be a nice complement to to-do lists as a way to make sure I'm doing the right things. Sciral Consistency is a rather more full featured implementation of the idea, but at the moment I'm finding the fact it sits nicely in my home page as more of an advantage, rather than having yet somewhere else to check.

My attempt at graph humour

I've been enjoying GraphJam for quite some time, so thought I'd have a go myself:

Distribution of question categories in Trivial Pursuit
moar funny pictures

February 17, 2010

Playing with Scala again...

Bought PDF version of Programming in Scala today, and seems pretty good so far. Definitely a step up from the already good (and free!) Scala by Example. Have just hacked the following to check my understanding of currying and by name functions:
scala> def times(n: Int)(op: => Unit) = { (1 to n).foreach(_ => op) }
times: (Int)(=> Unit)Unit

scala> times(4) { println("Hello") }
Hello
Hello
Hello
Hello