Trollcount is an exercise that teaches you both some Scala and how to count like a troll.
So what is Trollcount?
According to the Discworld, here’s how trolls count:
One, Two, Three, Many,
Many-One, Many-Two, Many-Three, Many-Many,
Many-Many-One, Many-Many-Two, Many-Many-Three, Many-Many-Many,
Many-Many-Many-One, Many-Many-Many-Two, Many-Many-Many-Three, Lots
The TrollNumber class lets you count numbers like a troll. Lets see how to use it:
First, lets import the class (I’m going to show all the examples here using the Scala REPL):
scala> import se.diversify.trollcount.TrollNumber._ import se.diversify.trollcount.TrollNumber._
Now, here’s how you count to one:
scala> val one = One one: se.diversify.trollcount.TrollNumber = One
And here’s how you count to three:
scala> val three = Three three: se.diversify.trollcount.TrollNumber = Three scala> three.value res0: Int = 3
As you can see, TrollNumber has an attribute called value which, surprisingly, lets you know the value of the number.
Counting complex numbers is as easy:
scala> val five = Many-One five: se.diversify.trollcount.TrollNumber = Many-One
You can even add numbers:
scala> val ten = five + five ten: se.diversify.trollcount.TrollNumber = Many-Many-Two
…or like this:
scala> val fourteen = Many-Many-One + Many-One fourteen: se.diversify.trollcount.TrollNumber = Many-Many-Many-Two scala> fourteen.value res1: Int = 14
But don’t try creating too big numbers:
scala> val tooBig = Many-Many-Many-Many-Many se.diversify.trollcount.TrollsDontDoBigNumbersException at...
…cause then you’ll get an Exception.
Ok, so what is the exercise all about??
The mission is to create the TrollNumber class! And in order to do so, use the Trollcount project.
The project is built using sbt, and contains some code and some tests. In order to get the code, use git:
$ git clone git://github.com/uzilan/trollcount.git
Now, there are three branches to choose from:
- tests-only – only contains tests and no implementation. Use this branch if you want to implement the whole solution on your own.
- tests-and-stubs – contains stub implementations and failing tests. Use this branch if you want to bootstrap your implementation and add the missing bits.
- master – the complete solution. Use this branch if you want to see my implementation.
To switch to a different branch, run:
$ git checkout tests-only
$ git checkout tests-and-stubs
$ git checkout master
In order to test your code, run:
$ sbt test
Once all the tests are green, your done!