tag:blogger.com,1999:blog-12272014539398277852024-02-19T06:50:24.194-08:00Careful Escapadesa blogg mainly about programming, politics and philosophy.Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.comBlogger12125tag:blogger.com,1999:blog-1227201453939827785.post-52559081950921199622012-05-07T12:51:00.001-07:002012-05-23T04:28:28.766-07:00Using implicit parameters for Dependency Injection in Scala<div dir="ltr" style="text-align: left;" trbidi="on">
A few days ago I made <a href="http://carefulescapades.blogspot.se/2012/05/problems-with-scala-cake-pattern-aka.html">a post</a> about some issues I have with the cake pattern for dependency injection. I want to illustrate a means of doing DI using scala's implicit parameters which retain the benefits of the cake pattern, but is more consice. The main benefit I see with the cake pattern is it's type safety. If we do something wrong the compiler will tell us, so we don't have to wait until we actually deploy to find out if our configuration is correct.<br />
<br />
In order to understand how to do DI with implicit parameters we need to understand how implicit parametrs are resolved in Scala. In essence if we define a method with an implicit parameter:<br />
<script class="brush: java" type="syntaxhighlighter">
scala> def implicitPrinter(implicit str:String) = println(str)
implicitPrinter: (implicit str: String)Unit
scala> implicitPrinter
<console>:9: error: could not find implicit value for parameter str: String
implicitPrinter
^
scala> implicit val abra = "abrakadabra"
abra: java.lang.String = abrakadabra
scala> implicitPrinter
abrakadabra
</script>
When the compiler finds a call to a method with an implicit parameter it searches for a implicit val/var/def/object that provide an instance of a matching type. In this case I defined method that take a string as an implicit parameter. When I tried to call it without having an implicit value of type String in scope I got an error. Then specified an implicit val, and calling the method now prints the value of that val. We can however override this behaviour by providing the method with an argument explicitly such as:<br />
<script class="brush: java" type="syntaxhighlighter">
scala> implicitPrinter("simzalabim")
simzalabim
</script>
For more information on how implicit parameters work and are resolved in Scala there are some excellent short blog posts on Daily Scala about it:
<ol style="text-align: left;">
<li><a href="http://daily-scala.blogspot.se/2010/04/companion-object-implicits.html">http://daily-scala.blogspot.se/2010/04/companion-object-implicits.html</a></li>
<li><a href="http://daily-scala.blogspot.se/2010/04/implicit-parameters.html">http://daily-scala.blogspot.se/2010/04/implicit-parameters.html</a></li>
<li><a href="http://daily-scala.blogspot.se/2010/04/implicit-parameter-resolution.html">http://daily-scala.blogspot.se/2010/04/implicit-parameter-resolution.html</a></li>
</ol>
<br />
From the last post the resolution rules for implicits is summarized as:<br />
<blockquote class="tr_bq">
There are very strict rules for which implicit value is to be applied to a implicit parameter. A simple way to think about it is that the "closest" definition will be used. Local scope, enclosing class, parent class, companion object of the desired type.</blockquote>
With this knowledge in our minds let's explore how we can use implicit parameters for dependency injection. For comparison I will show the same service/dao setup as in my <a href="http://carefulescapades.blogspot.se/2012/05/problems-with-scala-cake-pattern-aka.html">previous post</a>.<br />
<script class="brush: java" type="syntaxhighlighter">
trait FooService {
def allFoos:List[Foo]
}
class FooServiceImpl(implicit fooDao:FooDao) extends FooService {
def allFoos = fooDao.findAll
}
trait FooDao {
def findAll:List[Foo]
}
class FooDaoImpl extends FooDao {
def findAll = List(Foo(1), Foo(2))
}
</script>
Since an implicit parameter can be provided explicitly it is trivial to mock the FooDao when testing the FooServiceImpl. I think this is perhaps the main advantage of using DI. For comparison, using this means of dependency injection the code is succint and not poluted with alot of boilerplate (12 LoC compared to 25 LoC using the cake pattern). One issue still remains. How do we ensure that FooDao is injected into the FooServiceImpl?<br />
<script class="brush: java" type="syntaxhighlighter">
trait Conf {
private implicit val fooDao:FooDao = new FooDaoImpl // not visible in subclasses
implicit val fooService:FooService = new FooServiceImpl
}
// Then either:
object Conf extends Conf
class UIDependingOnConf {
def showFoos = {
val foos = Conf.fooService.allFoos
// rest of rendering code
}
}
// or:
class UIInheritingConf extends Conf {
def showFoos = {
val foos = fooService.allFoos
// rest of rendering code
}
}
</script>
The main difference between the two approaches above is that if we extend Conf in our class in order to get the dependencies we need then we will have several Conf instances around and all of them will contain a fooService and a fooDao. So I think the former approach is preferable for this reason.<br />
<br />
Another thing to notice is that in the Conf trait I have not explicitly provided FooServiceImpl with a FooDao when it is instantiated. Instead the compiler will resolve it for us using the locally defined fooDao val. Using this pattern we avoid having to spread a bunch of implicit val/def/var/object in our code. We have one central place where our configuration of the app is performed. If we make a mistake, such as defining two implicits with the same type in our conf so that the compiler don't know which to pick, we get a compiler error. Sweet!<br />
<br />
But, wait. What if we have a circular dependency? First, try to avoid circular dependencies. Second, we could resolve it by passing a factory function to the class:<br />
<script class="brush: java" type="syntaxhighlighter">
class BazService(implicit bizFunc:BazService => BizService) {
lazy val biz = bizFunc(this)
}
class BizService(implicit bazService:BazService)
</script>
Then in our configuration do something like:<br />
<script class="brush: java" type="syntaxhighlighter">
implicit val bizFunc = (bazService:BazService) => new BizService()(bazService)
</script>
Jonas Bonér has already described <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/">this pattern in his blog post</a> about different approaches to dependency injection. However, he states a thing I quite do not get:
<br />
<blockquote class="tr_bq">
This approach is simple and straight-forward. But I don’t really like that the actual wiring (importing the implicit declarations) is scattered and tangled with the application code.</blockquote>
This is obviously true if we choose to import the implicit definitions everywhere that we instantiate the classes. However, by using Conf as a factory for our dependencies we avoid having to import the implicits everywhere when we want a new instance of a certain "top level" class.</div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-80891211429525402782012-05-06T05:16:00.001-07:002012-05-08T06:33:52.630-07:00Problems with the Scala Cake Pattern - aka. Too much cake<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
A popular way to do dependency injection in Scala is to use the Cake pattern (see <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/">Jonas Boner's excellent blogg post about it</a>). This pattern involves specifying components using traits and specifying dependencies by using self-types. My main problem with the cake pattern is that it is very verbose. To illustrate let's look at how we can use dependency injection in Java using Spring:
<script class="brush: java" type="syntaxhighlighter">
public interface FooService {
List<foo> getAllFoos();
}
@Component("fooService")
public class FooServiceImpl implements FooService {
@Resource
private FooDao fooDao;
public List<foo> getAllFoos() {
return fooDao.findAll()
}
}
public interface FooDao {
List<foo> findAll();
}
@Component("fooDao")
public class FooDaoImpl {
public List<foo> findAll() {
return Arrays.asList(new Foo(1), new Foo(2));
}
}
</script>
<br />
This is 20 lines of code for a FooService that depends on a FooDao. To get this to work we would also need a few lines of XML configuration to enable component scanning etc.<br />
<br />
If we instead use the cake pattern we get the following.<br />
<script class="brush: scala" type="syntaxhighlighter">
trait FooServiceComponent {
def fooService:FooService
trait FooService {
def allFoos:List[Foo]
}
}
trait FooServiceComponentImpl extends FooServiceComponents {
this: FooDaoComponent =>
val fooService = new FooServiceImpl
trait FooServiceImpl extends FooService {
def allFoos = fooDao.findAll
}
}
trait FooDaoComponent {
def fooDao:FooDao
trait FooDao {
def findAll:List[Foo]
}
}
trait FooDaoComponentImpl extends FooDaoComponent {
val fooDao = new FooDaoImpl
trait FooDaoImpl extends FooDao {
def findAll = List(Foo(1), Foo(2))
}
}
</script>
<br />
This version is 25 lines of code. Sure, a separate xml file for the wireing is no longer necessary, we can just do:
<script class="brush: scala" type="syntaxhighlighter">
class FooComponent extends FooServiceComponentImpl with FooDaoComponentImpl<br />
</script>
But, the problem with the verbosity still remains. The java sample consist of 20 lines whereas the scala code is 25. I believe most developer would agree that Java is a very verbose language, despite this it is still more concise than the scala equivalent! That should ring an alarm bell. If we instead of java decided to use scala in the annotation driven way then we could shrink those 20 lines even further. While this might be ok if the proportions in LOC shifted when adding more components, but it does not. As we add more and more components the boilerplate necessary will further increase the difference!<br />
<br />
Of course LOC is not the whole story. We should also ask ourselves about the readability of the code. I have been using Spring quite a bit at work so my opinion is obviously biased because of it and I have not written alot of code using the cake pattern, but I think that the java/spring version is clearer. Also, you would likely end up having to specify all the vals and methods as protected in case you do not want to expose all the parts of the final component.<br />
<br />
To summarize the Cake pattern makes our code verbose and (to me) hard to read due to the boilerplate necessary. I also see some other minor problems with the pattern, but my main concern is that it adds a lot of noise to the code base.<br />
<br />
Should we just ditch the cake pattern and revert to using a DI framework like Spring? No. At least, I do not think so. Spring brings with it a bunch of fantastic features, but DI in Scala can be solved in a clean manner using some other language features. I will make a <a href="http://carefulescapades.blogspot.se/2012/05/using-implicit-parameters-for.html">post about it next</a>.<br />
<br /></div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-39108839340854571282010-07-26T04:10:00.000-07:002010-07-30T11:13:06.754-07:00Implementing Type Safe Roman Numerals in Scala (type parameter extravaganza!)I figured I wanted to do some more stuff with the roman numerals and try and create a type safe way to count with them (integers are so 2000 were living in the MMX now ;-)). Anyway what I wanted was something that could be used to express roman numerals in source files and that the compiler would say no if I expressed them in a flawed manner. It should be possible to write something like: MM I (1001), but it should not be possible to write: I MM (since that is not a proper roman numeral). <br /><br />I started out with a lass in Scala:<br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />class RomanNumeral(num:Int) {<br /> def toString = ... // See earlier post on the roman numeral kata<br />}<br />]]></script><br /><br />Then using some traits I could add the ability to express simple combinations of roman numerals:<br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />trait Numeral {<br /> def num:Int<br />}<br /><br />trait NumeralI extends Numeral<br /><br />trait NumeralV extends NumeralI {<br /> def I = new RomanNumeral(1 + this.num) with NumeralI<br /> def II = new RomanNumeral(2 + this.num) with NumeralI<br /> def III = new RomanNumeral(3 + this.num) with NumeralI<br />}<br /><br />//...<br /><br />trait NumeralM extends NumeralD {<br /> def CD = new RomanNumeral(400 + this.num) with NumeralC<br /> def D = new RomanNumeral(500 + this.num) with NumeralD<br /> def CM = new RomanNumeral(900 + this.num) with NumeralC<br />}<br /><br /><br />val I = new RomanNumeral(1) with NumeralI<br />val II = new RomanNumeral(2) with NumeralI<br />val III = new RomanNumeral(3) with NumeralI<br />val IV = new RomanNumeral(4) with NumeralI<br />val IX = new RomanNumeral(9) with NumeralI<br />val V = new RomanNumeral(5) with NumeralV<br />// ...<br />val M = new RomanNumeral(1000) with NumeralM<br />val MM = new RomanNumeral(2000) with NumeralM<br />val MMM = new RomanNumeral(3000) with NumeralM<br />]]></script><br /><br />After importing the RomanNumeral class and the traits along with the contents of the RomanNumerals object I was able to write M CD since scala interprets that as M.CD and since M (defined in the RomanNumerals object) extends the NumeralM trait it has a method CD. It would also not be possible to write I M since I only extends the trait NumeralI which does not define any M method. This is all well and good, but I wanted some more expressive power. I wanted to be able to write something along the lines of M CM X I (i.e. 1911), but that is not possible because the way scala interprets spaces M CM X I would be turned into: M.CM(X).I . That means my RomanNumeral would need an apply method that could take another RomanNumeral and return a new one. So I defined one:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br /> def apply(rn:RomanNumeral) = new RomanNumeral(this.num + rn.num)<br />]]></script><br /><br />Now atleast I was able to write M CM X (since that is "M.CM(X)") however I was also able to write M CM M (i.e. M.CM(M)), but that would be an illegal RomanNumeral (since the M CM is 1900 it doesn't make sense to have an M after it; L, X, V, I would all be valid but not M nor C). In addition I was not able to write M CM X I since the returned RomanNumeral from the apply method had no Numeral<i>N</i> mixed in when instantiated (using with). I would be able to write M.CM.X.I since that indicates to the compiler that I am calling a method on the return value of the previous method (i.e. calling the method X on the return value of the method CM and so on), but I wanted to do this without the dots :).<br /><br />So first things first; how could I know in th eapply method which trait I should mixin with the returned RomanNumeral so that it would have the appropriate methods available? Enter the type parameters. I first tried redefining the RomanNumeral class as follows:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />class RomanNumeral[T<:Numeral](val num: Int) {<br /> def apply[N >: T <: Numeral](rn:RomanNumeral[N]) = new RomanNumeral[N](this.num + rn.num) with N<br /> override def toString = num.toString<br />}<br />]]></script><br /><br />However that does not work. Why you ask? Well, first some explanation of the type parameters introduced. The type parameters for the RomanNumeral is specified with T<:Numeral the <:Numeral part is a upper bound on the type that can be used for the class. So instantiating a RomanNumeral I would atleast have to pass in a Numeral or a subclass thereof. In the apply method I specify an upper and a lower bounds for the type parameter of the RomanNumeral passed in as an argument to the method. The lower bounds on the type parameter is T and the upper bound is Numeral so the type used as a type parameter of the RomanNumeral being passed to the method has to atleast be a Numeral and at most be a T (which in turn has to be a subtype of Numeral). A few examples in the interpreter might be helpfull here... (lets ignore the "with N" part of the code above)<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />scala> val five = new RomanNumeral[NumeralV](5)<br />five: RomanNumeral[NumeralV] = 5<br />scala> val three = new RomanNumeral[NumeralI](3)<br />three: RomanNumeral[NumeralI] = 3<br /><br />scala> five(three) // works fine<br />res68: RomanNumeral[NumeralI] = 8<br /><br />scala> three(five) // gives a type mismatch error<br /><console>:14: error: type mismatch;<br /> found : RomanNumeral[NumeralV]<br /> required: RomanNumeral[NumeralI]<br /> three(five)<br /> ^<br />scala> five(five)<br />res70: RomanNumeral[NumeralV] = 10<br /><br />scala> three(three)<br />res71: RomanNumeral[NumeralI] = 6<br />]]></script><br /><br />Since NumeralI is a super class of NumeralV and a subclass of Numeral the "five" value can be supplied with the "three" value to its apply method. Doing the reverse causes a type missmatch since NumeralV is not a superclass of NumeralI. Method apply would look like this in the first instance (with the type parameters spelt out):<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />five.apply[NumeralI >: NumeralV <: Numeral](rn:RomanNumeral[NumeralI]) = ...<br />]]></script><br /><br />and in the latter case:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />three.apply[NumeralV >: NumeralI <: Numeral](rn:RomanNumeral[NumeralV]) = ... <br />// ^ ^<br />// NumeralV is not a super class of NumeralI<br />]]></script><br /><br />All this is a ok. So why doesn't the RomanNumeral code above compile? Well, because of type erasure for one and also because N could be a concrete class and not a trait(only traits can be mixed in to classes at instantiation time). After type erasure there is no way of knowing what N is and therefore the RomanNumeral class above would not compile. At this point I tried alot of different version of the above to find something which did work. In the end I realized that I could have an apply method that took a Numeral<i>N</i> instead and have one for each trait. That way I would know which type should be mixed in with the RomanNumeral.<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />class RomanNumeral[T<:Numeral](val num: Int) {<br /> def apply(rn:NumeralI) = <br /> new RomanNumeral[NumeralI](this.num + rn.num) with NumeralI<br /><br /> def apply(rn:NumeralV) = <br /> new RomanNumeral[NumeralV](this.num + rn.num) with NumeralV<br /><br /> def apply(rn:NumeralX) = <br /> new RomanNumeral[NumeralX](this.num + rn.num) with NumeralX<br /><br /> def apply(rn:NumeralL) = <br /> new RomanNumeral[NumeralL](this.num + rn.num) with NumeralL<br /><br /> def apply(rn:NumeralC) = <br /> new RomanNumeral[NumeralC](this.num + rn.num) with NumeralC<br /><br /> def apply(rn:NumeralD) = <br /> new RomanNumeral[NumeralD](this.num + rn.num) with NumeralD<br /><br /> override def toString = num.toString<br />}<br />]]></script><br /><br />This worked fine, but allowed any Numeral to follow any other. Using the interpreter to illustrate:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />scala> val three = new RomanNumeral[NumeralI](1) with NumeralI<br />three: RomanNumeral[NumeralI] with NumeralI = 1<br /><br />scala> val five = new RomanNumeral[NumeralV](5) with NumeralV<br />five: RomanNumeral[NumeralV] with NumeralV = 5<br /><br />scala> three(five) // should not work<br />res73: RomanNumeral[NumeralV] with NumeralV = 6<br /><br />scala> five(three) // should be ok<br />res74: RomanNumeral[NumeralI] with NumeralI = 6<br />]]></script><br /><br />As can be seen above a NumeralI could be followed by a NumeralV which should not be allowed. By changing the NumeralI and its subtypes to take a type parameter I was able to add the type bounds back to the apply methods and enforce the correct behaviour. The traits now looks like this:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br /> trait Numeral {<br /> def num:Int<br /> }<br /><br /> trait NumeralI[N<:Numeral] extends Numeral<br /> trait NumeralV[N<:Numeral] extends NumeralI[N] {<br /> def I = new RomanNumeral[Numeral](1 + this.num) with Numeral<br /> def II = new RomanNumeral[Numeral](2 + this.num) with Numeral<br /> def III = new RomanNumeral[Numeral](3 + this.num) with Numeral<br /> }<br /> <br /> trait NumeralX[N<:Numeral] extends NumeralV[N] {<br /> def IV = new RomanNumeral[Numeral](4 + this.num) with Numeral<br /> def V = new RomanNumeral[NumeralI[Numeral]](5 + this.num) with NumeralV[NumeralI[Numeral]]<br /> def IX = new RomanNumeral[Numeral](9 + this.num) with Numeral<br /> }<br /><br /> trait NumeralL[N<:Numeral] extends NumeralX[N] {<br /> def X = new RomanNumeral[NumeralV[Numeral]](10 + this.num) with NumeralX[NumeralV[Numeral]]<br /> def XX = new RomanNumeral[NumeralV[Numeral]](20 + this.num) with NumeralX[NumeralV[Numeral]]<br /> def XXX = new RomanNumeral[NumeralV[Numeral]](30 + this.num) with NumeralX[NumeralV[Numeral]]<br /> }<br /><br />...<br /><br /> trait NumeralM[N<:Numeral] extends NumeralD[N] {<br /> def CD = new RomanNumeral[NumeralL[Numeral]](400 + this.num) with NumeralC[NumeralL[Numeral]]<br /> def D = new RomanNumeral[NumeralC[Numeral]](500 + this.num) with NumeralD[NumeralC[Numeral]]<br /> def CM = new RomanNumeral[NumeralL[Numeral]](900 + this.num) with NumeralC[NumeralL[Numeral]]<br /> }<br />]]></script><br /><br />And the RomanNumeral class looks like:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />class RomanNumeral[T<:Numeral](val num:Int) {<br /> def apply[N >: T <: Numeral](rn:NumeralI[N]) = <br /> new RomanNumeral[Numeral](rn.num + num) with Numeral<br /><br /> def apply[N >: T <: Numeral](rn:NumeralV[N]) = <br /> new RomanNumeral[NumeralI[Numeral]](rn.num + num) with NumeralV[NumeralI[Numeral]]<br /> <br /> def apply[N >: T <: Numeral](rn:NumeralX[N]) = <br /> new RomanNumeral[NumeralV[Numeral]](rn.num + num) with NumeralX[NumeralV[Numeral]]<br /><br /> def apply[N >: T <: Numeral](rn:NumeralL[N]) = <br /> new RomanNumeral[NumeralX[Numeral]](rn.num + num) with NumeralL[NumeralX[Numeral]]<br /><br /> def apply[N >: T <: Numeral](rn:NumeralC[N]) = <br /> new RomanNumeral[NumeralL[Numeral]](rn.num + num) with NumeralC[NumeralL[Numeral]]<br /> <br /> def apply[N >: T <: Numeral](rn:NumeralD[N]) = <br /> new RomanNumeral[NumeralC[Numeral]](rn.num + num) with NumeralD[NumeralC[Numeral]]<br /><br /> override def toString = // See earlier post on the roman numeral kata<br />}<br />]]></script><br /><br />With these modifications I could now specify the values in ther RomanNumerals object as follows:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br /> val I = new RomanNumeral[NumeralI[Numeral]](1) with NumeralI[Numeral]<br /> val II = new RomanNumeral[NumeralI[Numeral]](2) with NumeralI[Numeral]<br /> val III = new RomanNumeral[NumeralI[Numeral]](3) with NumeralI[Numeral]<br /> val IV = new RomanNumeral[NumeralI[Numeral]](4) with NumeralI[Numeral]<br /> val V = new RomanNumeral[NumeralI[Numeral]](5) with NumeralV[NumeralV[Numeral]]<br /> val IX = new RomanNumeral[NumeralI[Numeral]](9) with NumeralI[Numeral]<br /> val X = new RomanNumeral[NumeralV[Numeral]](10) with NumeralX[NumeralX[Numeral]]<br /><br /> ...<br /><br /> val M = new RomanNumeral[NumeralD[Numeral]](1000) with NumeralM[NumeralM[Numeral]]<br /> val MM = new RomanNumeral[NumeralD[Numeral]](2000) with NumeralM[NumeralM[Numeral]]<br /> val MMM = new RomanNumeral[NumeralD[Numeral]](3000) with NumeralM[NumeralM[Numeral]]<br /> implicit def num2RomanNumeral(n:Number):RomanNumeral[Numeral] = <br /> new RomanNumeral[Numeral](n.intValue)<br />]]></script><br /><br />By importing all the classes and traits and then importing the contents of the RomanNumerals object (import RomanNumerals._) I can now write my roman numerals in a type safe way. I.e. M C X V I (which is equivalent of writing: M.C.apply(X).V.apply(I) ) is allowed but M CM C is not allowed. Why? Well, since the return value of the CM method is a RomanNumeral with the type parameters NumeralL[Numeral] (and with NumeralL[Numeral] mixed in) the apply methods all look like:<br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br /> def apply[N >: NumeralL[Numeral] <: NumeralI/V/X/L/C/D[Numeral]] = ...<br />]]></script><br />and C has the type RomanNumeral[NumeralC[Numeral]] with NumeralC[Numeral] there is no apply method where C is a valid argument (C is a NumeralC[Numeral] which is a subtype of NumeralL[Numeral] and as such violates the lower bounds on the type parameter). <br /><br />Next I created a rollover so that when a RomanNumeral is created that is larger than 3999 it rolls over to a number which can be described with roman numerals (i.e. > 0 and < 4000). Then to wrapp things up I simply added a companion object with an apply/unapply method to my RomanNumeral so it can easily be used in pattern matching. I also added some methods for basic arithmatic (+-/*), implemented the Ordered trait and extended the Number class. Finally I added an implicit conversion from Number to a RomanNumeral[Numeral] so that I could add Integers and Doubles and such to a RomanNumeral and vice versa (with a result type of a RomanNumeral[Numeral]).<br /><br />The final result can be seen below (now I only need to find a problem for my solution :-) ):<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />package org.mediocre.scalakatas<br /><br />object RomanNumerals {<br /> import annotation._<br /><br /> trait Numeral {<br /> def num:Int<br /> }<br /><br /> class RomanNumeral[T<:Numeral](n:Int) extends Number with Ordered[RomanNumeral[Numeral]] {<br /> private val MAX_ROMAN = 3999<br /> val num = if(n > 0 && n % MAX_ROMAN != 0) n % MAX_ROMAN else (n % MAX_ROMAN) + MAX_ROMAN<br /><br /> def compare(that:RomanNumeral[Numeral]) = this.num compare that.num<br /> def +(number:Number) = new RomanNumeral[Numeral](num + number.intValue)<br /> def -(number:Number) = new RomanNumeral[Numeral](num - number.intValue)<br /> def *(number:Number) = new RomanNumeral[Numeral](num * number.intValue)<br /> def /(number:Number) = new RomanNumeral[Numeral](num / number.intValue)<br /><br /> def apply[N >: T <: Numeral](rn:NumeralI[N]) = <br /> new RomanNumeral[Numeral](rn.num + num) with Numeral<br /><br /> def apply[N >: T <: Numeral](rn:NumeralV[N]) = <br /> new RomanNumeral[NumeralI[Numeral]](rn.num + num) with NumeralV[NumeralI[Numeral]]<br /> <br /> def apply[N >: T <: Numeral](rn:NumeralX[N]) = <br /> new RomanNumeral[NumeralV[Numeral]](rn.num + num) with NumeralX[NumeralV[Numeral]]<br /><br /> def apply[N >: T <: Numeral](rn:NumeralL[N]) = <br /> new RomanNumeral[NumeralX[Numeral]](rn.num + num) with NumeralL[NumeralX[Numeral]]<br /><br /> def apply[N >: T <: Numeral](rn:NumeralC[N]) = <br /> new RomanNumeral[NumeralL[Numeral]](rn.num + num) with NumeralC[NumeralL[Numeral]]<br /> <br /> def apply[N >: T <: Numeral](rn:NumeralD[N]) = <br /> new RomanNumeral[NumeralC[Numeral]](rn.num + num) with NumeralD[NumeralC[Numeral]]<br /> override def intValue = num<br /> override def byteValue = num.toByte<br /> override def floatValue = num.toFloat<br /> override def doubleValue = num.toDouble<br /> override def longValue = num.toLong<br /> <br /> override def equals(that:Any) = <br /> that.isInstanceOf[RomanNumeral[Numeral]] && num == that.asInstanceOf[RomanNumeral[Numeral]].num<br /> override def hashCode = num<br /> override def toString = {<br /> @tailrec<br /> def innerLoop(int:Int, count:Int, <br /> sb:StringBuilder, <br /> rPair:(Int,String)):(StringBuilder, Int, Int) = {<br /> if(int > 0 && count > 0 <br /> && rPair._1 > 0 <br /> && (int - rPair._1) >= 0) {<br /> if(count > int) {<br /> innerLoop(int, count - rPair._1, sb, rPair)<br /> } else {<br /> sb.append(rPair._2)<br /> innerLoop(int - rPair._1, count, sb, rPair)<br /> }<br /> } else {<br /> (sb, int, rPair._1)<br /> }<br /> }<br /> <br /> val listOfPairs:List[(Int,String)] = <br /> (1000, "M")::(900, "CM")::<br /> (500, "D")::(400, "CD")::<br /> (100, "C")::(90, "XC")::<br /> (50, "L")::(40, "XL")::<br /> (10, "X")::(9, "IX")::<br /> (5,"V")::(4, "IV")::<br /> (1,"I")::Nil<br /><br /> listOfPairs.foldLeft((new StringBuilder(), num, 3999))(<br /> (sbNumCounter,romanNumPair) => {<br /> val (sb, int, counter) = sbNumCounter<br /> innerLoop(int, counter, sb, romanNumPair) <br /> })._1 toString<br /> }<br /> }<br /><br /> object RomanNumeral {<br /> def apply[T<:Numeral](int:Int) = new RomanNumeral[T](int)<br /> def unapply(rn:RomanNumeral[Numeral]) = Some(rn.num)<br /> }<br /><br /> trait NumeralI[N<:Numeral] extends Numeral<br /> trait NumeralV[N<:Numeral] extends NumeralI[N] {<br /> def I = new RomanNumeral[Numeral](1 + this.num) with Numeral<br /> def II = new RomanNumeral[Numeral](2 + this.num) with Numeral<br /> def III = new RomanNumeral[Numeral](3 + this.num) with Numeral<br /> }<br /> <br /> trait NumeralX[N<:Numeral] extends NumeralV[N] {<br /> def IV = new RomanNumeral[Numeral](4 + this.num) with Numeral<br /> def V = new RomanNumeral[NumeralI[Numeral]](5 + this.num) with NumeralV[NumeralI[Numeral]]<br /> def IX = new RomanNumeral[Numeral](9 + this.num) with Numeral<br /> }<br /><br /> trait NumeralL[N<:Numeral] extends NumeralX[N] {<br /> def X = new RomanNumeral[NumeralV[Numeral]](10 + this.num) with NumeralX[NumeralV[Numeral]]<br /> def XX = new RomanNumeral[NumeralV[Numeral]](20 + this.num) with NumeralX[NumeralV[Numeral]]<br /> def XXX = new RomanNumeral[NumeralV[Numeral]](30 + this.num) with NumeralX[NumeralV[Numeral]]<br /> }<br /><br /> trait NumeralC[N<:Numeral] extends NumeralL[N] {<br /> def XL = new RomanNumeral[NumeralV[Numeral]](40 + this.num) with NumeralX[NumeralV[Numeral]]<br /> def L = new RomanNumeral[NumeralX[Numeral]](50 + this.num) with NumeralL[NumeralX[Numeral]]<br /> def XC = new RomanNumeral[NumeralV[Numeral]](90 + this.num) with NumeralX[NumeralV[Numeral]]<br /> }<br /><br /> trait NumeralD[N<:Numeral] extends NumeralC[N] {<br /> def C = new RomanNumeral[NumeralL[Numeral]](100 + this.num) with NumeralC[NumeralL[Numeral]]<br /> def CC = new RomanNumeral[NumeralL[Numeral]](200 + this.num) with NumeralC[NumeralL[Numeral]]<br /> def CCC = new RomanNumeral[NumeralL[Numeral]](300 + this.num) with NumeralC[NumeralL[Numeral]]<br /> }<br /><br /> trait NumeralM[N<:Numeral] extends NumeralD[N] {<br /> def CD = new RomanNumeral[NumeralL[Numeral]](400 + this.num) with NumeralC[NumeralL[Numeral]]<br /> def D = new RomanNumeral[NumeralC[Numeral]](500 + this.num) with NumeralD[NumeralC[Numeral]]<br /> def CM = new RomanNumeral[NumeralL[Numeral]](900 + this.num) with NumeralC[NumeralL[Numeral]]<br /> }<br /><br /> val I = new RomanNumeral[NumeralI[Numeral]](1) with NumeralI[Numeral]<br /> val II = new RomanNumeral[NumeralI[Numeral]](2) with NumeralI[Numeral]<br /> val III = new RomanNumeral[NumeralI[Numeral]](3) with NumeralI[Numeral]<br /> val IV = new RomanNumeral[NumeralI[Numeral]](4) with NumeralI[Numeral]<br /> val V = new RomanNumeral[NumeralI[Numeral]](5) with NumeralV[NumeralV[Numeral]]<br /> val IX = new RomanNumeral[NumeralI[Numeral]](9) with NumeralI[Numeral]<br /> val X = new RomanNumeral[NumeralV[Numeral]](10) with NumeralX[NumeralX[Numeral]]<br /> val XX = new RomanNumeral[NumeralV[Numeral]](20) with NumeralX[NumeralX[Numeral]]<br /> val XXX = new RomanNumeral[NumeralV[Numeral]](30) with NumeralX[NumeralX[Numeral]]<br /> val XL = new RomanNumeral[NumeralV[Numeral]](40) with NumeralX[NumeralX[Numeral]]<br /> val L = new RomanNumeral[NumeralX[Numeral]](50) with NumeralL[NumeralL[Numeral]] <br /> val XC = new RomanNumeral[NumeralV[Numeral]](90) with NumeralX[NumeralX[Numeral]]<br /> val C = new RomanNumeral[NumeralL[Numeral]](100) with NumeralC[NumeralC[Numeral]]<br /> val CC = new RomanNumeral[NumeralL[Numeral]](200) with NumeralC[NumeralC[Numeral]] <br /> val CCC = new RomanNumeral[NumeralL[Numeral]](300) with NumeralC[NumeralC[Numeral]] <br /> val CD = new RomanNumeral[NumeralL[Numeral]](400) with NumeralC[NumeralC[Numeral]]<br /> val D = new RomanNumeral[NumeralC[Numeral]](500) with NumeralD[NumeralD[Numeral]]<br /> val CM = new RomanNumeral[NumeralL[Numeral]](900) with NumeralC[NumeralC[Numeral]] <br /> val M = new RomanNumeral[NumeralD[Numeral]](1000) with NumeralM[NumeralM[Numeral]]<br /> val MM = new RomanNumeral[NumeralD[Numeral]](2000) with NumeralM[NumeralM[Numeral]]<br /> val MMM = new RomanNumeral[NumeralD[Numeral]](3000) with NumeralM[NumeralM[Numeral]]<br /> implicit def num2RomanNumeral(n:Number):RomanNumeral[Numeral] = <br /> new RomanNumeral[Numeral](n.intValue)<br />}<br />]]></script>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-4353061882704145942010-07-21T01:55:00.000-07:002010-07-21T02:01:19.565-07:00Roman Numerals Kata in ScalaI got back to work monday this week after roughly 12 month of parental leave (Sweden has some awesome benefits). Since the office is realy quite and I am sitting idle with no assignment I figured that I would spend my time doing some Katas in Scala. At the last Scala Meetup in Gothenburg (which I unfortunately missed) they did the <a href="http://www.codingdojo.org/cgi-bin/wiki.pl?KataRomanNumerals">Roman Numerals Kata</a> and I figured I'd implement that to start. I have decided to go back to basics with my coding after tiering of Eclipse going real sluggish for the umphteenth time and as such I have installed <a href="www.gnu.org/software/emacs/">emacs</a> once again. There is a basic scala-mode for emacs that is distributed with the Scala release and there is also an compliment to it named <a href="http://github.com/aemoncannon/ensime">Ensime</a> that is under development and adds some nice features, such as code completion, sbt integration, inspection of types, etc etc. So after installing emacs, Scala, Ensime and <a href="http://code.google.com/p/simple-build-tool/">SBT (Simple Build Tool)</a> I started on the kata. <br /><br />I usually like to start out writing tests for my code and Specs provides a pretty nice DSL way to do that. Here is the tests for my ArabicRomanConverter:<br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />import org.specs._<br /><br />object ArabicRomanConverterSpec extends Specification {<br /> "The converter" should {<br /> "convert sample integers between 1 and 3999 correctly" in {<br /> ArabicRomanConverter(1745) must beSome("MDCCXLV")<br /> ArabicRomanConverter(33) must beSome("XXXIII")<br /> ArabicRomanConverter(45) must beSome("XLV")<br /> }<br /> "not convert an integer less than 1" in {<br /> ArabicRomanConverter(0) must beNone<br /> ArabicRomanConverter(-1) must beNone<br /> ArabicRomanConverter(-9999) must beNone<br /> }<br /> "not convert an integer greater than 3999" in {<br /> ArabicRomanConverter(3999) must beSome("MMMCMXCIX")<br /> ArabicRomanConverter(4000) must beNone<br /> ArabicRomanConverter(9999) must beNone<br /> }<br /> "convert spimple cases for integers correctly " in {<br /> ArabicRomanConverter(1) must beSome("I")<br /> ArabicRomanConverter(4) must beSome("IV")<br /> ArabicRomanConverter(5) must beSome("V")<br /> ArabicRomanConverter(9) must beSome("IX")<br /> ArabicRomanConverter(10) must beSome("X")<br /> ArabicRomanConverter(40) must beSome("XL")<br /> ArabicRomanConverter(50) must beSome("L")<br /> ArabicRomanConverter(90) must beSome("XC")<br /> ArabicRomanConverter(100) must beSome("C")<br /> ArabicRomanConverter(400) must beSome("CD")<br /> ArabicRomanConverter(500) must beSome("D")<br /> ArabicRomanConverter(900) must beSome("CM")<br /> ArabicRomanConverter(1000) must beSome("M")<br /> }<br /> "convert the integer 1999 to the string 'MCMXCIX'" in {<br /> ArabicRomanConverter(1999) must beSome("MCMXCIX")<br /> }<br /> }<br />}<br />]]></script><br />All in all pretty simple tests for border cases, the different simple cases along with a few randomly chosen numbers. Onward to the implementation code!<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />import annotation._<br /><br />object ArabicRomanConverter {<br /><br /> private val listOfPairs:List[(Int,String)] = (1000, "M")::(900, "CM")::<br /> (500, "D")::(400, "CD")::<br /> (100, "C")::(90, "XC")::<br /> (50, "L")::(40, "XL")::<br /> (10, "X")::(9, "IX")::<br /> (5,"V")::(4, "IV")::<br /> (1,"I")::Nil<br /><br /> def apply(int:Int):Option[String] = {<br /> if(int < 1 || int > 3999) {<br /> None<br /> } else {<br /> Some(convert(int))<br /> }<br /> }<br />]]></script><br />Here the apply function takes care of my input sanity checks, verifying that the number is actually convertable to roman numbers (at least to the roman numbers of the magnitude I am interested in). The listOfPairs is used in the convert method below.<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br /> private def convert(int:Int):String = {<br /><br /> @tailrec def innerLoop(num:Int, count:Int, <br /> sb:StringBuilder, <br /> rPair:(Int,String)):(StringBuilder, Int, Int) = {<br /> if(num > 0 && count > 0 <br /> && rPair._1 > 0 <br /> && (num - rPair._1) >= 0) {<br /> if(count > num) {<br /> innerLoop(num, count - rPair._1, sb, rPair)<br /> } else {<br /> sb.append(rPair._2)<br /> innerLoop(num - rPair._1, count, sb, rPair)<br /> }<br /> } else {<br /> (sb, num, rPair._1)<br /> }<br /> }<br /> <br /> listOfPairs.foldLeft((new StringBuilder(), int, 3999))(<br /> (sbNumCounter,romanNumPair) => {<br /> val (sb, num, counter) = sbNumCounter<br /> innerLoop(num, counter, sb, romanNumPair) <br /> })._1 toString<br /> }<br />}<br />]]></script><br /><br />In the convert function I have defined an recursive function called innerLoop and annoted it with @tailrec. The annotation tells the compiler to optimize the function to a loop and gives an error if the function is not tail recursive. The innerLoop is tail recursive because the last opperation in the function is a call to itself or the return value for the function as a whole. <br /><br />So what does the innerLoop actually do? Well it starts out by checking if we are done and should return the StringBuilder-Num-Counter-tuple by verifying that "num", "count", the int in the "rPair" tuple are all greater than 0 (basically just a precaution). It also checks if it is "safe" to subtract the integer in the "rPair" tuple from "num". Then if the "count" is greater than "num", "count" should be decremented by the integer in the "rPair" tuple, otherwise "num" should be decremented and the String in the "rPair" tuple appended to the StringBuilder. In both cases we do a recursive call to innerLoop and try again. The innerLoop function gets called from within the foldLeft over the "listOfPairs". So basically for each romanNumPair we attempt to subtract the integer in the pair from the "num" (in the innerLoop) as many times as possible (and still keeping "num" greater than or equal to 0). The StringBuilder is then extracted from the result of the foldLeft and converted to a String.<br /><br />Having completed the kata I started to ponder if there isn't a better way. The roman numbers aren't actually Strings but Numbers and it would be cool if you could add, subtract, multiply and divide them as such. So I have decided to check if there is an easy and clean way to do this in Scala... more on that another time perhaps.Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com1tag:blogger.com,1999:blog-1227201453939827785.post-51274316210424743072010-04-27T06:39:00.000-07:002010-04-27T06:40:50.502-07:00A-star Scala implementation...Working on my game I decided to do a generic version of the A* graph search algorithm. Below are the results. Basically pass in your start- and goal node, a neighbor funciton, a heuristic funciton (which needs to be not only admissable but also consistent) i.e. straight line distance, cost function between two nodes (the A* implementation will only pass in neighboring nodes as argument to the cost function).<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />import scala.collection.mutable.Set<br /><br />object PathFinder {<br /> <br /> def apply[T](start:T, goal:T, neighbors:T => List[T], heuristic:(T,T)=>Float, costFunc:(T,T)=>Float):List[T] = {<br /> def calculateCost(path:(Float, List[T])) =<br /> path._2.tail.foldLeft((0f,path._2.head))((costHead,node) => {<br /> val (cost, head) = costHead<br /> (cost + costFunc(node,head), node)<br /> })._1<br /><br /> def findBestCandidate(candidates:Set[(Float, List[T])]) =<br /> candidates.foldLeft(<br /> (Float.PositiveInfinity, (0f, List[T]())))((best, path) => {<br /> val guesstimate = path._1 + heuristic(path._2.head, goal)<br /> if (best._1 < guesstimate) best else (guesstimate,path)<br /> })._2<br /><br /> // Uses mutable set for performance... ?<br /> var fringe = Set((0f,start::Nil))<br /> var closed = Set[T]()<br /><br /> while(!fringe.isEmpty) {<br /> val (cost, current) = findBestCandidate(fringe)<br /> fringe = fringe - ((cost, current))<br /> if(current.head equals goal)<br /> return current.reverse<br /> else if (!closed.contains(current.head )) {<br /> closed = closed + current.head<br /> neighbors(current.head).foreach(n => {<br /> val nCost = costFunc(current.head, n) + cost<br /> fringe = fringe + ((nCost, n::current))<br /> })<br /> }<br /> }<br /> // Searched all possible paths...<br /> return Nil<br /> }<br />}<br />]]></script><br /><br />Not sure if the internal use of a mutable set to keep track of the fringe and closed nodes is optimal...<br /><br /><br />Cheers,<br /> Emil HAnonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com1tag:blogger.com,1999:blog-1227201453939827785.post-48053060151821251212010-04-10T14:42:00.000-07:002010-04-15T00:55:22.677-07:00I made a floor (more Scala and JMonkeyEngine)!I've played around with Scala and JMonkeyEngine some more. It is always a supprise when you've been working on something and then you get an epiphany "Oh, I shouldn't do it like this...", then you change the way you go about the problem and you're basically done in five minutes. Well, ideally that is... This time that is what coding my Floor/Game Board implementation felt like. <br /><br />I got the tip to use SharedMesh on the JME forum. This felt like a good fit for my floor since each Tile would be exactly the same. Initially I had created each tile with its own vertices, colors, indices and normals array. With the SharedMesh all Tiles share the data in these arrays. Niffty :)<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />object Tile extends TriMesh("HexTileTriMesh", TileValues.vertices(),TileValues.normals(),TileValues.colors(),TileValues.texCoords(),TileValues.indices()) {<br /> def apply(name:String, xOffset:Float, zOffset:Float):Tile = {<br /> return new Tile(name,xOffset,zOffset)<br /> }<br /> <br />}<br /><br />class Tile(name:String, xOffset:Float, zOffset:Float) extends SharedMesh(name, Tile) {<br /> this.setLocalTranslation(xOffset, 0, zOffset)<br />}<br />]]></script><br />So here I use the singleton object Tile as the TriMesh for the Tile class. I think this is a nice fit. There will only ever be a single instance of the TriMesh used to create the floor and if I later need to change some property of the floor I can just change the values in the Tile object. So when creating a new Tile I just use the apply method of the Tile object, pass in a name and the x an z offset. This is done in the Floor object below. The Floor class is basically just a Node at the moment, but I expect will grow when I start building the actual game :) The magic happens yet again in the companion object.<br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />class Floor(name:String) extends Node(name) {<br /><br />}<br /><br />object Floor {<br /> // The z distance between rows<br /> val zShift = Math sqrt(0.75) toFloat<br /> def apply(name:String, cols:Int, rows:Int):Floor = {<br /> val floor = new Floor(name)<br /> // calculate the number of tiles to be created<br /> val numberOfTiles = ((cols * rows) + ((cols * rows) % 2)) / 2<br /> // Start creating floor tiles...<br /> (0 to numberOfTiles - 1).foldLeft((0f,0f, 0, 0))(<br /> (pos,tileNr) => {<br /> val (x,z,col,row) = pos<br /> // create a tile with offset x and z<br /> val t = Tile(name + "_Tile" + tileNr, x, z )<br /> // make a bounding box around it<br /> t.setModelBound(new BoundingBox())<br /> // update the bounds so they get computed correctly...<br /> t.updateModelBound<br /> // attatch the tile to the floor<br /> floor.attachChild(t)<br /> // calculate the values of the pos Tuple<br /> calculatePos(x,z,col,row, cols)<br /> })<br /><br /> floor<br /> }<br /><br /> private def calculatePos(x:Float,z:Float,col:Int,row:Int, cols:Int):(Float,Float,Int,Int) = {<br /> // Check how we should shift x and z<br /> (col + 2 >= cols, cols) match {<br /> case (true,1) =><br /> // Corner case where we have a single column...<br /> (0, z+2*zShift, 0, row + 1)<br /> case (true, _) =><br /> // If we are on an even row add<br /> // 1.5 to x and set col to start at 1<br /> // Otherwise set x and col to 0<br /> // Always shift z by zShift (to new row)<br /> // and increment row number...<br /> (1.5f * ((row + 1) % 2), z+zShift, 1 * ((row + 1) % 2), row + 1)<br /> case (false, _) =><br /> // Add 3 to x and 2 to col<br /> (x + 3, z, col + 2, row)<br /> }<br /> }<br />}<br />]]></script><br />I have to say I realy like foldLeft and I have missed it since I stopped coding in Erlang. Everything becomes nice and clean with it. You pass in some state to a Itterable along with a function (that returns a new state) to apply for each element. No mutables that change and cause strange bugs. Sweet. Oh, and another nice feature in Scala is pattern matching. I use it in the calculatePos method. This case is a very basic example of pattern matching (I could have used a simple if-elseif-else instead) and it can be much more powerful.<br /><br />And here is the result:<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3E9iO-_IOA4W0IXAkhVRc5BRaf6Vgclcet19pQK84DfHc6EFqJq-dPS_uU1fTBlcXuMI8DMKF85VsgteCmYix2-90_ootlyepfcXGmhPd3PcPxzVxRqb1el2lS5y14Zx-skPItkB-3MdI/s1600/Floor.png"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 246px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3E9iO-_IOA4W0IXAkhVRc5BRaf6Vgclcet19pQK84DfHc6EFqJq-dPS_uU1fTBlcXuMI8DMKF85VsgteCmYix2-90_ootlyepfcXGmhPd3PcPxzVxRqb1el2lS5y14Zx-skPItkB-3MdI/s320/Floor.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5460269321887820658" /></a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />Next step will be to create a figure to move about my new floor, some pathfinding in a hexgrid (I think JME has an A* implementation, so I'll have a look at that). Later I'll add some basic controlls to the game.<br /><br />Cheers,<br /> Emil HAnonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-72546387747386378482010-04-08T09:09:00.000-07:002010-04-08T10:21:19.901-07:00Scala and JMonkeEngine 2I've started a small game development project for funsies. Getting JME2 to work properly on my linux box was a bit of a hassel initally since I wanted to have it work with maven. After a bit of tinkering and following the slightly dated <a href="http://jmonkeyengine.com/wiki/doku.php/jme_maven_setup">tutorial</a> (most of it is still correct as of March 2010) I got everything running smothly with a Hello3D sample in Java. However, since I wanted to use Scala 2.8, I realized I had to update Netbeans to 6.8 and get the new Scala plugin for it. So to get going a little faster I skipped the maven part for now. Setup is always easier the second time around I have noticed. <br /><br />With my environment setup I created a Scala project. Included the lwjgl-, jinput- and the jme-2.0 jar and added the native bindings to the VM options. And I was ready to go!<br /><br />So I quickly ran into a problem that is due to (I believe) the scala-netbeans plugin, a import error "jme is not a member of com". It seems that the issue is that the plugin had not realized that I had included the libraries. When I restarted Netbeans the following generated no errors:<br /><br /><script type="syntaxhighlighter" class="brush: scala"><![CDATA[<br />package playground<br /><br />import com.jme._<br />import app.AbstractGame.ConfigShowMode<br />import app.SimpleGame<br />import scene.shape.Box<br />import math.Vector3f<br />import bounding.BoundingBox<br /><br />object Main extends SimpleGame {<br /><br /> /**<br /> * @param args the command line arguments<br /> */<br /> def main(args: Array[String]): Unit = {<br /> this.setConfigShowMode(ConfigShowMode.AlwaysShow)<br /> this.start()<br /> }<br /><br /> override def simpleInitGame() = {<br /> this.display.setTitle("Playground!")<br /> val box = new Box("my box", new Vector3f(0, 0, 0), 1,2,3)<br /> box.setModelBound(new BoundingBox())<br /> box.updateModelBound()<br /> this.rootNode.attachChild(box)<br /> }<br /><br />}<br />]]></script><br /><br />A few nice features in Scala can be seen here. First, importing using a wildcard i.e. "somepackage._". In the case above I imported "com.jme._" because of that I dont have to write the entire package name for all the things I import from a subpackage of jme. Instead I can write, for instance, "app.SimpleGame" to import that class from "com.jme.app.SimpleGame". Not the greatest thing in the world, but a good thing to know when looking at Scala code, and it does clean the import statements up.<br /><br />The object keyword in Scala defines a "singleton object". What this means is that there will only ever be a single instance of that object. It's kind of like a Java class with only static methods. So why is this useful? Well, for starters Scala doesn't allow static methods so it's needed to create the entry point for the program. But, there is also something called companion objects (I'll talk about them another time) and that is when objects shine :)<br /><br />The rest of the code is very similar to Java code. However, we can notice that the val "box" has no declared type. "box" still has a type of course, which is inferred by the scala compiler from the assignment to it. This cuts down on a bunch of boiler-plate. Oh, and "val" is a variable which can only be assigned to once (like a variable marked with the final keyword in Java). There is also "var" which is mutable.<br /><br />I expect to see more Scala power once I get things rolling, for instance a DSL for the core game rules would be nice. I'll have to come back to that...<br /><br />Cheers,<br /> - Emil HAnonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-63123065905690215562009-12-07T13:43:00.000-08:002009-12-07T13:53:04.560-08:00First Steps... (oh that is truely cheesy)I've managed to clean up the Steps code a little bit. It is now possible to use the SampleTrackerSite to upload, download and search for torrent files. The Peer tracking also works, however it is not able to respond with the compact peer list, i.e. it will always respond with a bencoded dictionary for each peer. I'm going to add the compact response next. In addition I will move the model to use JPA instead of the built in Mapper stuff. That way Steps will be able to run on GAE, which I think would be nice...<div><br /></div><div>Next post I will attempt to do a short presentation of a feature I like in Scala. It will either be case classes or mixins. But, I'm not sure I use mixins "correctly" ;)</div><div><br /></div><div>PS. If anyone try to use the Steps code please send an e-mail, especially if there are any issues (I'm sure there are several I overlooked). Oh and Steps can be found at <a href="http://github.com/archevel/Steps">http://github.com/archevel/Steps</a>!</div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-13461597595338869142009-11-23T05:50:00.000-08:002009-11-23T05:56:55.998-08:00Ubuntu saves me again...So I managed to screw up my boot loader when I wanted to try if a game I play ran better in Win XP than in Win 7 (there was some graphics lag issue). Anyhow, I always have a live ubuntu cd lying around for such circumstances and it saved me having to reinstall my entire system yet again. <div><br /></div><div>In the end I disabled the booting from my primary drive in the OS and let Win 7 repair the damaged bootmanager. So now everything (almost) is back to it's original state... but I think I'll throw back GRUB and let it handle the booting for me :)</div><div><br /></div><div>And again... ALWAYS keep a live cd of some linux distro at hand!</div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-27876147238303058582009-11-13T11:41:00.000-08:002009-11-13T12:04:01.011-08:00It's on githubI've created a public repository on github to host the code for my Scala bittorrent tracker. As for now I have decided to call it Steps. A tracker follows steps, a "Scala" (stair in italian) has steps, however Lift (the webframework that Steps uses) lacks it... so Steps is a nice name.<div><br /></div><div>The git repo can be found here:<br /><a href="http://github.com/archevel/Steps">http://github.com/archevel/Steps</a></div><div><br /></div><div>Right now the only usable code there is the Bencoder, which can be used to decode a Byte array of bencoded data into Scala objects (SortedMap, List, String and Int) and encode them back. I have a working Tracker implementation, but I want to clean the code up a bit before committing it and try to get some more tests together for it. Real soon now :)</div><div><br /></div><div>Ps. I forgot to say that you can also find the repo by searching on google for "scala bittorrent steps" currently it's the 10th hit Ds.</div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-29610761815647156592009-11-11T04:54:00.000-08:002009-11-11T05:06:42.898-08:00And he is asleep...Now that Sebastian is taking his afternoon nap I have time to do some coding. A couple of month ago I attempted to hack-away with my son in my lap. It was not an experience which captured the imagination of my then 8 month year old son. Nowadays he seems to prefer to stand up beside things... who am I to judge? I enjoy coding in my spare time, he likes to stand. I suppose the standing thing is in most cases more usefull.<div><br /></div><div>What am I coding then? Well, I have made a bittorrent tracker written in Scala and using Lift. Lift is a nice framework, fairly easy to get into (if you have some form of book or guide). The hardest part I think is getting used to code in Scala. I'll post some nifty language features later.</div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0tag:blogger.com,1999:blog-1227201453939827785.post-1992225407286132452009-11-11T02:51:00.000-08:002009-11-11T04:54:05.367-08:00Building a "Koja" with Sebastian...<div xmlns="http://www.w3.org/1999/xhtml"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIYfNyhuUjGfkspefNtmYNekw24eKiwHaJGDCJlmcCKD5Qtvi9KO_ivi4BuixrHMn4fyhszvDJiQs7dZOOf_0MO_QaeRfLqkAwno6vLz7zC6XSYn9-IF0Nms8yK4YcKZWQzCJ5gqype5WN/s1600-h/image-upload-50-720232.jpg"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIYfNyhuUjGfkspefNtmYNekw24eKiwHaJGDCJlmcCKD5Qtvi9KO_ivi4BuixrHMn4fyhszvDJiQs7dZOOf_0MO_QaeRfLqkAwno6vLz7zC6XSYn9-IF0Nms8yK4YcKZWQzCJ5gqype5WN/s320/image-upload-50-720232.jpg" /></a><br /><span><br /></span></div>Anonymoushttp://www.blogger.com/profile/08943845201323990515noreply@blogger.com0