Been fun running this blog, but now it's time for me too to move back to my old blog:
http://christiangenne.blogspot.com
Hope to see you there!
And Gustaf, thank you :)
/ Christian
Sunday, August 9, 2009
Sunday, August 2, 2009
Gustaf moves to his own blog.
From now on, I (Gustaf) will post all my posts on my original blog, http://gustafnilssonkotte.blogspot.com/. I would be very (!) happy if you added that feed to your readers.
Sorry for the inconvenience.
Christian: Thank you for a very nice time buddy! :)
/Gustaf
Sorry for the inconvenience.
Christian: Thank you for a very nice time buddy! :)
/Gustaf
Tuesday, June 2, 2009
Objective-C... yet another programming language?
Just recently installed XCode on my mac in order to develop applications for my iPhone. The first thing I realized was that I needed to learn yet another programming language. Just another syntax, or does Objective-C actually bring something new?
It turns out Objective-C (which is a language derived from C, similar to C++, but still very different) has one feature I haven't seen before. First of, instead of calling a method on an object, your send a message to it. It's almost the same, but also requires you to pass along named parameters (which means more code to write, but easier to read). The new and cool feature appears when you want to send a message to an object, which should return a value, when the object turns out to be nil.
So when executing this code, as opposed to how normal programming languages handles it, it doesn't crash. It simply returns 0.0 if the expected return type is a number, or nil if the expected return type is a pointer to an object. This also works for functions returning nothing (i.e. void), sending a void returning message to a nil object will simpy do nothing.
In for example C# you always have to do null checks all over the code, in order to verify your object isn't nil.
I'm not sure I like it or not, but if you learn to think "pure Objective-C" then perhaps this can be used as an advantage! I'm looking forward to learning Objective-C further, and to adapt these new concepts!
I'll let you know when I've published my first iPhone app :)
It turns out Objective-C (which is a language derived from C, similar to C++, but still very different) has one feature I haven't seen before. First of, instead of calling a method on an object, your send a message to it. It's almost the same, but also requires you to pass along named parameters (which means more code to write, but easier to read). The new and cool feature appears when you want to send a message to an object, which should return a value, when the object turns out to be nil.
MyClass* myObject = nil;
if ([myObject getValue] == 0.0) {
// myObject getValue retuned 0, OR myObject is nil
}
So when executing this code, as opposed to how normal programming languages handles it, it doesn't crash. It simply returns 0.0 if the expected return type is a number, or nil if the expected return type is a pointer to an object. This also works for functions returning nothing (i.e. void), sending a void returning message to a nil object will simpy do nothing.
In for example C# you always have to do null checks all over the code, in order to verify your object isn't nil.
I'm not sure I like it or not, but if you learn to think "pure Objective-C" then perhaps this can be used as an advantage! I'm looking forward to learning Objective-C further, and to adapt these new concepts!
I'll let you know when I've published my first iPhone app :)
Saturday, April 25, 2009
From for loop to anamorphism
Introduction
Sometimes you want to generate a sequence of objects. This is often done using a for loop:
[Test]
public void CreateListOfFoos()
{
var xs = new List<Foo>();
for (int i = 0; i < 10; i++)
{
xs.Add(new Foo());
}
Assert.AreEqual(10, xs.Count());
}
In this post, I will show you how this code can be made more general, ultimately turning it into an anamorphism over lists.
Generalizing constructed type
First, what we want to do is to be able to create something other than a Foo. We apply ExtractVariable once and we also extract the constructor call to a lambda:
[Test]
public void ExtractMethod()
{
var times = 10;
Func<Foo>newFoo = () => new Foo();
var xs = CreateFooNumberOfTimes(times, newFoo);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<Foo> CreateFooNumberOfTimes(int times, Func<Foo> newFoo)
{
var xs = new List<Foo>();
for (int i = 0; i < times; i++)
{
xs.Add(newFoo.Invoke());
}
return xs;
}
From the above code, it’s easy to generalize on the type created. Note that we could have skipped the “constructor lambda” and instead used the “where T : new()” constraint.
[Test]
public void GeneralizeTypeForFunc()
{
var times = 10;
Func<Foo> newFoo = () => new Foo();
var xs = CreateTNumberOfTimes(times, newFoo);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<T> CreateTNumberOfTimes<T>(int times, Func<T> newFoo)
{
var xs = new List<T>();
for (int i = 0; i < times; i++)
{
xs.Add(newFoo.Invoke());
}
return xs;
}
Generalizing type for accumulator
We have now parametrized Foo to T, but wouldn’t it be possible to parametrize from “int” to A, as well? Let’s begin with breaking out the int-specific code from the for loop:
[Test]
public void ExtractForLoopLogic()
{
Func<Foo> newFoo = () => new Foo();
int i = 0; // Will be modified lots of times
Func<bool> expr = () => i < 10;
Action inc = () => i++;
var xs = CreateTUntil(newFoo, expr, inc);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<T>CreateTUntil<T>(Func<T> newT, Func<bool> expr, Action inc)
{
var xs = new List<T>();
for (; expr.Invoke(); inc.Invoke())
{
xs.Add(newT.Invoke());
}
return xs;
}
As indicated in the code, the variable “i” will be modified the closure called in CreateTUntil. Bart de Smet calls this a cruel lambda. Except that it’s quite hard to understand a lambda that mutate its outer scope, refactoring code that’s using cruel lambdas can make your code go totally bananas!
Let’s rewrite the code to use a pure lambdas instead. To do this, we need to refactor the for loop to a while loop, since the first and third “parameters” to a for loop are statements (not pure). We also parametrize from “int” to type parameter “A” instead.
Going pure and a more general constructor
[Test]
public void ForLoopToWhileLoop()
{
Func<Foo> newFoo = () => new Foo();
Func<int,bool> expr = a => a < 10;
Func<int,int> inc = i => i + 1;
var xs = CreateTUntilUsingWhile(newFoo, 0, expr, inc);
Assert.AreEqual(10, xs.Count());
}
// Now a pure method
private IEnumerable<T> CreateTUntilUsingWhile<T>
(Func<T> newT, int init, Func<int,bool> expr, Func<int,int> inc)
{
var xs = new List<T>();
int i = init;
while (expr.Invoke(i))
{
xs.Add(newT.Invoke());
i = inc.Invoke(i);
}
return xs;
}
Now we don’t have any concrete types in the method signature, except bool, which I think is ok to have there at this point. But, as the observant reader might have noticed, the constructor can’t be called with a variable argument, i.e. the accumulated value. What we need to do is to “connect” the lambdas that generates values, like this:
[Test]
public void ArgumentForConstructor()
{
Func<int,Result<Foo,int>> gen = n => new Result<Foo,int>(new Foo(), n + 1);
Func<int,bool> expr = a => a < 10;
var xs = GeneralizedCreateTWithArgsUntilUsingWhile(gen, 0, expr);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<T> GeneralizedCreateTWithArgsUntilUsingWhile<T,A>
(Func<a,Result><T,A>> gen, A init, Func<A,bool> expr)
{
var xs = new List<T>();
var i = init;
while (expr.Invoke(i))
{
var result = gen.Invoke(i);
xs.Add(result.Value);
i = result.Accumulator;
}
return xs;
}
Going recursive
Now it’s up to the generating lambda to pass an argument to the constructor or not. What’s funny with this is that if we replace the while loop to a recursive call, we come pretty close to the definition of an anamorphism over lists in the introduction of Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire by Erik Meijer et. al (link to postscript version).
[Test]
public void WhileLoopToRec()
{
Func<int, Result<Foo, int>> gen = n => new Result<Foo, int>(new Foo(), n + 1);
Func<int, bool> expr = a => a < 10;
var xs = CreateTUntilUsingRec(gen, 0, expr);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<T> CreateTUntilUsingRec<T,A>
(Func<A, Result<T, A>> gen, A init, Func<A, bool> expr)
{
if (!expr.Invoke(init))
return new List<T>();
var result = gen.Invoke(init);
return (new List<T> {result.Value})
.Concat(CreateTUntilUsingRec(gen, result.Accumulator, expr));
}
Abstracting away from bool
It seems that the only thing left to do is to abstract away the dependency on “bool” in CreateTUsingRec, but then we bump into a small problem,as you will see. What we do is to join the two lambdas into one and performing a null check inside the recursive function.
[Test]
public void MergeOnceMore()
{
int? i = 0;
Func<int, Result<int?, int>> gen = n => new Result<int?, int>(n < 10 ? i : null, n + 1);
var xs = CreateTUntilUsingRecNullCheck(gen, 0);
Assert.AreEqual(10, xs.Count());
}
private IEnumerable<T> CreateTUntilUsingRecNullCheck<T, A>
(Func<A, Result<T, A>> gen, A init)
{
var result = gen.Invoke(init);
if (result.Value == null)
return new List<T>();
return (new List<T> { result.Value })
.Concat(CreateTUntilUsingRecNullCheck(gen, result.Accumulator));
}
Writing it in F# instead
The problem with this solution is that we have lost the ability to generate ordinary non-nullable structs and that’s bad! We could easily solve the problem with writing our own MyNullable<T> which would allow both classes and structs as instantiators of the type variable, but instead of doing that, I’ll show you something similar: the option type in F#.
let rec anamorphism n f =
match f n with
| option.None -> []
| option.Some (e,next) -> e::(anamorphism next f)
> anamorphism 0 (fun a -> if a < 5 then option.Some("Bar" + a.ToString(), a + 1) else option.None);;
val it : string list = ["Bar0"; "Bar1"; "Bar2"; "Bar3"; "Bar4"]
Here, we removed the Result class and used a pair instead, together with the Option type, which is essentially the same as Nullable<T>, but without the restriction on type.
Conslusion
Functional programming is perhaps more abstract than imperative programming, but it is also seems to be more general, at least in this case. This post has only showed an anamorphism over lists, which is the simple case. Look here if you want to see a more advanced example.
Wednesday, March 4, 2009
Why you love and hate Ruby
What strikes me when programming Ruby is how simple everything is! You've got utility functions for almost everything, and writing an application doesn't take more then a few lines of code. No need to setup a project, no need to think about types. You just write code!
The downside of this, of course, is that the code easily becomes bad written, and as there are very few rules in Ruby, it isn't very easy reading others' code. This is why Ruby sometimes is classified as a "hard to lean language". There are simply too many ways of writing the same code.
I don't agree that this makes the language more hard to learn, but perhaps makes it take longer to learn the language fully. For instance, I just recently learned you can write code in the following way:
I've never seen code like that before, but it really opens up for some nice syntax!
Another feature of Ruby is that Classes are open, and everything is an object, meaning you can extend/modify classes on the fly. Even classes are objects! For example:
The syntax is almost perfect! How would you otherwise say "5 minutes ago"? That's what people often talk about when they describe Ruby. "The only truly object oriented language".
Why Ruby isn't the perfect language, IMO, is because it's too "open". There are too many ways of writing code. Writing smaller applications, or better scripts, won't take you more than a few minutes, but when you need to work on a larger project, I would definitely go with a strictly typed language, such as C#, where you have better control over your code. Also, not surprisingly, no IDE can help you writing your code, as the code is dynamically typed, and you really can't say what functions are available on an object until you actually run the code.
So, thumb up for this language when working on smaller applications. But for larger projects, I would recommend going for another one.
The downside of this, of course, is that the code easily becomes bad written, and as there are very few rules in Ruby, it isn't very easy reading others' code. This is why Ruby sometimes is classified as a "hard to lean language". There are simply too many ways of writing the same code.
I don't agree that this makes the language more hard to learn, but perhaps makes it take longer to learn the language fully. For instance, I just recently learned you can write code in the following way:
puts "Hello my friend" if userIsFriendly
I've never seen code like that before, but it really opens up for some nice syntax!
Another feature of Ruby is that Classes are open, and everything is an object, meaning you can extend/modify classes on the fly. Even classes are objects! For example:
class Fixnum
def minutes
return Timespan.new(self)
end
end
class Timespan
def ago
return Time.now - self
end
end
5.minutes.ago
The syntax is almost perfect! How would you otherwise say "5 minutes ago"? That's what people often talk about when they describe Ruby. "The only truly object oriented language".
Why Ruby isn't the perfect language, IMO, is because it's too "open". There are too many ways of writing code. Writing smaller applications, or better scripts, won't take you more than a few minutes, but when you need to work on a larger project, I would definitely go with a strictly typed language, such as C#, where you have better control over your code. Also, not surprisingly, no IDE can help you writing your code, as the code is dynamically typed, and you really can't say what functions are available on an object until you actually run the code.
So, thumb up for this language when working on smaller applications. But for larger projects, I would recommend going for another one.
Thursday, February 26, 2009
Fluent language in FsStory
A nice feature for a story runner is to be able to provide arguments in a story sentence, like this:
ATableWithNumberOfLegs 4
This example is not hard to understand, but there's some mental translation going on, since the order of the words is all screwed up. Let's try another one:
TheNumberOfLegsOfATableIs 4
Better, but still not good. First, it's longer than the previous example. Second, even if the grammar is correct, the word order is, well, unusual.. ;)
What about this?
ATableWith 4 Legs
Now we're talking!
Here's a bigger and more complete example:
Note: As far as I know, RSpec/Cucumber is the only story runner(s) that is able to use variables inside a story sentence.
The nice thing about this is that I didn't have to change FsStory itself to make it work. Not a single line. So, what's the trick?
If you split up a story sentence like this, you have to prepare the step definition code (the behind-the-scenes code) in a certain way:
let ATableWith = fun n _ -> ... do something here ...
..or if you prefer, without a lambda:
let ATableWith n _ = ... do something here ...
Then you have to define Legs:
let Legs = id
As you see, in this case, it was just a matter of discovering the usage, rather than implementing it in the language. Honestly, I had no idea of this usage when I started to write on FsStory. This is clearly one of the reasons why I like internal DSLs!
Exercise: How would you implement the step definition for the following story sentence?
given (ATableWith 4 LegsAnd 2 Chairs)
Cheers!
ATableWithNumberOfLegs 4
This example is not hard to understand, but there's some mental translation going on, since the order of the words is all screwed up. Let's try another one:
TheNumberOfLegsOfATableIs 4
Better, but still not good. First, it's longer than the previous example. Second, even if the grammar is correct, the word order is, well, unusual.. ;)
What about this?
ATableWith 4 Legs
Now we're talking!
Here's a bigger and more complete example:
[<Fact>]
let tableLegsScenario =
given (ATableWith 4 Legs)
|> whens (ICutOf 1 Leg)
|> thens (ItHasOnly 3 LegsLeft)
Note: As far as I know, RSpec/Cucumber is the only story runner(s) that is able to use variables inside a story sentence.
The nice thing about this is that I didn't have to change FsStory itself to make it work. Not a single line. So, what's the trick?
If you split up a story sentence like this, you have to prepare the step definition code (the behind-the-scenes code) in a certain way:
let ATableWith = fun n _ -> ... do something here ...
..or if you prefer, without a lambda:
let ATableWith n _ = ... do something here ...
Then you have to define Legs:
let Legs = id
As you see, in this case, it was just a matter of discovering the usage, rather than implementing it in the language. Honestly, I had no idea of this usage when I started to write on FsStory. This is clearly one of the reasons why I like internal DSLs!
Exercise: How would you implement the step definition for the following story sentence?
given (ATableWith 4 LegsAnd 2 Chairs)
Cheers!
Sunday, February 22, 2009
ImpossibleEstimation and Pomodoro Technique
Sometimes when using Pomodoro Technique I find it real difficult to estimate how long a particular activity will take, i.e., when locating a bug or find out why the webserver won't read my files.
In Pomodoro Technique, every activity should have a time estimate - how many Pomodori I think it will take. Though, this is sometimes impossible! "The problem is solved when I find the bug and since I don't know what the bug is related to, it's impossible to say how much time it will take to find it."
The solution: instead of just writing a number besides the activity, I use the less-than sign (<) before the number, indicating that I have a time-box for the activity, but that it might take less time. If I'm not done when the time-box is over, I have to ask a colleague to help me or ask my boss for extra resources - thus, escalating my problem. Then, I'm forced to have collected some data of the problem to help them to help me. The nice thing is that I still can have most of the benefits Pomodoro Technique gives me, i.e., increased focus when in a Pomodoro and possibility to get "the whole picture" during my breaks. The latter have proved to be an extra nice thing to have during hard problem-solving.
And, if a colleague comes to the rescue, we can construct another time-box, to know when to escalate it further, or at least to notify the team or the boss that we have some nasty problems at hand.
Yet, if I'm collecting metrics of my estimation skills, it is not a very good idea to track data for these bug-fixing Pomodori estimates. Put a "N/A" or a "-" in your records sheet and think for yourself: "Today was an exception, tomorrow will be a bug-free day." And don't forget to do your daily mind-map before you leave for home.
In Pomodoro Technique, every activity should have a time estimate - how many Pomodori I think it will take. Though, this is sometimes impossible! "The problem is solved when I find the bug and since I don't know what the bug is related to, it's impossible to say how much time it will take to find it."
The solution: instead of just writing a number besides the activity, I use the less-than sign (<) before the number, indicating that I have a time-box for the activity, but that it might take less time. If I'm not done when the time-box is over, I have to ask a colleague to help me or ask my boss for extra resources - thus, escalating my problem. Then, I'm forced to have collected some data of the problem to help them to help me. The nice thing is that I still can have most of the benefits Pomodoro Technique gives me, i.e., increased focus when in a Pomodoro and possibility to get "the whole picture" during my breaks. The latter have proved to be an extra nice thing to have during hard problem-solving.
And, if a colleague comes to the rescue, we can construct another time-box, to know when to escalate it further, or at least to notify the team or the boss that we have some nasty problems at hand.
Yet, if I'm collecting metrics of my estimation skills, it is not a very good idea to track data for these bug-fixing Pomodori estimates. Put a "N/A" or a "-" in your records sheet and think for yourself: "Today was an exception, tomorrow will be a bug-free day." And don't forget to do your daily mind-map before you leave for home.
Monday, February 9, 2009
[Announce] FsStory, executable stories in F#
Since Claudio Perrone's talk on Øredev, I have been thinking about what his MisBehave would look like in F#. In his talk, Claudio also mentioned Cucumber, a story runner written in Ruby. My plan was to make a lightweight DSL for writing stories in F# code, with the story parts separated from the implementation parts.
Currently, FsStory enables the developer to write user story scenarios (in Given/When/Then form) in F# code, like this:
Did you notice [<fact>] attribute just before the function definition? It is a xUnit.net specific attribute, telling xUnit.net that the function is a runnable test. So, why xUnit.net? Answer: xUnit.net is the currently the only test framework that runs static test methods, which is what F# functions compiles to.
Note: If you think that the story above is too low level to be a "good" user story, you're right, but it's just an example..
The "ATurtle", "IsRotated90DegreesToTheRight", "TurtleWalksSteps", etc, are functions that you have to implement yourself. What these functions do is not FsStory's business, except that they have the same type. It's a good thing to think about this in advance.
If you're testing something object oriented, i.e. a C# project, then you're probably have to let the functions have the type () -> (). That is, they take no argument and return void, in C# lingo. You'd also need a mutable variable to accomplish this.
It's up to the developer what library she wants to use for her assertions. In this example, FsTest was used, but she could go for NUnit or NBehave or something else. I hadn't actually tried this and do not longer think this will work. Either use xUnit.net or FsTest (which is based on xUnit.net).
Another style is to work with immutable objects. One example of immutable objects are value objects, in DDD. Immutable objects correspond well to functional programming principles. Here is an example of an implementation of a scenario when an immutable object is used in the SUT (System Under Test).
To clarify, all methods on the (immutable) turtle return a new turtle and that turtle is returned and then passed in as an argument to the next test function (by FsStory). As you might have spotted, the example uses a lambda, an anonymous functions (the "fun") instead of specifying an argument explicitly. It's a good thing to get a running story before actually implementing the logic and assertions. Using the function "id" (just returning the argument) on the right-hand side is very helpful for getting everything to run.
You can find FsStory at http://www.codeplex.com/fsstory.
Currently, FsStory enables the developer to write user story scenarios (in Given/When/Then form) in F# code, like this:
#light
open FsStoryRunner
open MutatedTurtleMovesImpl
open Xunit
(*
In order to impress my friends
As a .NET programmer
I want to draw funny fractal pictures
*)
[<fact>]
let MoveTurtleToPosition() =
given ATurtle
|> andGiven IsRotated90DegreesToTheRight
|> whens (TurtleWalksSteps 9)
|> thens (TurtleIsLocatedAt (0,9))
|> endStory
Did you notice [<fact>] attribute just before the function definition? It is a xUnit.net specific attribute, telling xUnit.net that the function is a runnable test. So, why xUnit.net? Answer: xUnit.net is the currently the only test framework that runs static test methods, which is what F# functions compiles to.
Note: If you think that the story above is too low level to be a "good" user story, you're right, but it's just an example..
The "ATurtle", "IsRotated90DegreesToTheRight", "TurtleWalksSteps", etc, are functions that you have to implement yourself. What these functions do is not FsStory's business, except that they have the same type. It's a good thing to think about this in advance.
If you're testing something object oriented, i.e. a C# project, then you're probably have to let the functions have the type () -> (). That is, they take no argument and return void, in C# lingo. You'd also need a mutable variable to accomplish this.
#light
open Turtle
open FsxUnit.Syntax
let mutable turtle = new Turtle() // turtle must have type Turtle
let ATurtle () = turtle <- new Turtle() // For reuse in same story let MovesOneStepForward () = turtle.Go() let IsMovedOneStepForward () = turtle.Position.X |> should equal 1 let RotationIs angle () = turtle.Direction |> should equal 0.0
Another style is to work with immutable objects. One example of immutable objects are value objects, in DDD. Immutable objects correspond well to functional programming principles. Here is an example of an implementation of a scenario when an immutable object is used in the SUT (System Under Test).
let ATurtle () = new TurtleImmutable()
let IsRotated90DegreesToTheRight = fun (turtle : TurtleImmutable) -> turtle.Left()
let TurtleWalksSteps steps = fun (turtle : TurtleImmutable) -> turtle.GoSteps(steps)
let TurtleIsLocatedAt (x,y) = fun (turtle : TurtleImmutable) -> turtle.Position |>
should equal (new Position(x,y)) ; turtle
To clarify, all methods on the (immutable) turtle return a new turtle and that turtle is returned and then passed in as an argument to the next test function (by FsStory). As you might have spotted, the example uses a lambda, an anonymous functions (the "fun") instead of specifying an argument explicitly. It's a good thing to get a running story before actually implementing the logic and assertions. Using the function "id" (just returning the argument) on the right-hand side is very helpful for getting everything to run.
You can find FsStory at http://www.codeplex.com/fsstory.
Friday, February 6, 2009
Trying out ruby for the very first time
So, I've made up my mind. The language of this year is going to be Ruby! The reasons are many, but mostly I feel I can use this language more in my daily work, and on a podcast over at AltDotNet about Ruby, they mentioned something like "learning ruby will make you a better C# developer". Languages like lisp and python will have to wait for at least one year!
About two weeks ago, I was out skiing with Gustaf and some friends of him. We ended up playing a lot of four in a row, a really funny and simple game. This game made me think about how to develop a min max AI, and suddenly I had written down the pseudo code for such an AI in my notebook. Here is a picture of the game is supposed to be played (from wikipedia):
Now, back home at my computer, I started digging into the ruby documentations, and after not more than a few hours I had finished the first version of the AI! Turns out Ruby isn't that hard to learn, at least not if you just want to get some basic things done. It's like writing c#, except you skip the types, and instead of writing void foo(int x) { ... } you write def foo(x) ... end, and so on...
Here is how my final version of the game looks when you run it:
and so on...
I wonder how much code can you post in a blog, without the post becoming too long? I would like to post the code as an attachment, but I'm not sure you can do that in blogger, so I'll simply put it here. To try it out, copy the code to a file, i.e. 4inarow.rb, then run it using ruby 4inarow.rb. Enjoy ;)
About two weeks ago, I was out skiing with Gustaf and some friends of him. We ended up playing a lot of four in a row, a really funny and simple game. This game made me think about how to develop a min max AI, and suddenly I had written down the pseudo code for such an AI in my notebook. Here is a picture of the game is supposed to be played (from wikipedia):
Here is how my final version of the game looks when you run it:
C:\Documents and Settings\Christian\Desktop>ruby 4irad.rb
Run against ai (A), another player (P) or let two AIs play against eachother (X)
A
Enter AI 1 level (1 to 5):
3
Enter name of human player (default Human 1):
---------------
|0 1 2 3 4 5 6|
---------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
---------------
AI 1 (3) played: 3
---------------
|0 1 2 3 4 5 6|
---------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |O| | | |
---------------
Human 1, make your move:
2
Human 1 played: 2
---------------
|0 1 2 3 4 5 6|
---------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |X|O| | | |
---------------
AI 1 (3) played: 3
---------------
|0 1 2 3 4 5 6|
---------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |O| | | |
| | |X|O| | | |
---------------
Human 1, make your move:
and so on...
I wonder how much code can you post in a blog, without the post becoming too long? I would like to post the code as an attachment, but I'm not sure you can do that in blogger, so I'll simply put it here. To try it out, copy the code to a file, i.e. 4inarow.rb, then run it using ruby 4inarow.rb. Enjoy ;)
$debugEnabled = false
def debug(text)
if $debugEnabled then
puts ">>> " + text
end
end
class State
attr_reader :cols, :rows, :player, :winner, :lastPlayed, :isFull
Player1 = "Player 1"
Player2 = "Player 2"
def initialize
@cols = []
(0..6).each { @cols << [] }
@rows = []
(0..5).each { @rows << Array.new(7, nil) }
@player = Player1
@winner = nil
@isFull = false
end
def deep_copy
return Marshal.load( Marshal.dump( self ) )
end
def to_s
return "---------------\n" +
"|" + (0..6).to_a.join(" ") + "|\n" +
"---------------\n" +
@rows.reverse.collect{|row| "|" + row.collect{|r| if !r then " " elsif r == Player2 then "X" else "O" end}.join("|") + "|"}.join("\n") + "\n" +
"---------------"
end
def canPlay( i )
return @winner == nil && @cols[i].length < 6
end
def play( i )
if canPlay i then
rowIndex = @cols[i].length
@cols[i] << @player
@rows[rowIndex][i] = @player
@lastPlayed = i
switchPlayer
updateWinner
updateIsFull
end
end
def updateIsFull
for p in @rows[5]
if !p then return end
end
@isFull = true
end
def findWinner( row )
for i in 0..(row.length-4)
p = nil
n = 0
for j in 0..3
rp = getPlayed(row[i+j])
if rp.class != Fixnum then
if !p then
p = rp
elsif p != rp
p = 0
break
end
if rp != 0 then
n += 1
end
end
end
if p != 0 and n == 4 then
return p
end
end
return nil
end
def updateWinner
for row in getAllRanges
p = findWinner row
if p then
@winner = p
end
end
end
def switchPlayer
if @player == Player1 then
@player = Player2
else
@player = Player1
end
end
def getPlayed(cell)
c = cell[0]
r = cell[1]
col = @cols[c]
if r >= col.length then
return r - col.length + 1
end
return @cols[c][r]
end
def posValid( c, r )
return c >= 0 && c <= 6 && r >= 0 && r <= 5
end
def getDiagonal( c, r, dc )
d = []
while posValid( c, r )
d << [c, r]
c += dc
r += 1
end
return d
end
def getAllDiagonalsRanges
diags = []
for r in 0..5
diags << getDiagonal( 0, r, 1 )
end
for c in 1..6
diags << getDiagonal( c, 0, 1 )
end
for r in 0..5
diags << getDiagonal( 6, r, -1 )
end
for c in 0..5
diags << getDiagonal( c, 0, -1 )
end
return diags
end
def getAllColsRanges
return (0..6).collect{|c| (0..5).collect{|r| [c, r]}}
end
def getAllRowsRanges
return (0..5).collect{|r| (0..6).collect{|c| [c, r]}}
end
def getAllRanges
return getAllColsRanges +
getAllRowsRanges +
getAllDiagonalsRanges
end
end
class Node
attr_reader :state, :children, :isLeaf
def initialize( state, player )
if !player then
raise "player is nil"
end
@state = state
@isLeaf = true
@children = {}
@player = player
end
def getPoints( row )
points = 0.0
for i in 0..(row.length-4)
p = nil
n = 0
divider = 1
for j in 0..3
rp = @state.getPlayed(row[i+j])
if rp.class == Fixnum then
divider *= rp
else
if !p then
p = rp
elsif !rp then
elsif p != rp
p = nil
break
end
if rp then
n += 1
end
end
end
if p then
blockPoints = calculatePoints n / divider
if p == @player then
points += blockPoints
else
points = points - blockPoints
end
end
end
if points.infinite? then
debug "Found winner: " + points.to_s + ": " + row.join("|")
end
return points
end
def calculatePoints( n )
return n.to_f**3 / (4 - [n,4].min)
end
def nodePoints
points = 0.0
for row in state.getAllRanges
p = getPoints(row)
if p != 0 then
#debug row.collect{|r| if r then r else " " end}.join("|") + " " + p.to_s
end
newPoints = points + p
if newPoints.nan? then
raise "points + p == NaN: points=" + points.to_s + " p=" + p.to_s
end
points = newPoints
end
#puts state
#puts "Points: " + points.to_s
return points
end
def allChildPoints
return children.values.collect {|child| child.totalPoints}
end
def isMyTurn
return state.player == @player
end
def totalPoints
if @totalPoints then
return @totalPoints
end
p = nil
if @isLeaf then
p = nodePoints
else
if isMyTurn then
p = allChildPoints.max
else
p = allChildPoints.min
end
end
if !p then
raise "nil points returned"
end
@totalPoints = p
return p
end
def grow
if @totalPoints then
#puts "Gah, totalPoints is set"
@totalPoints = nil
end
if @isLeaf && !@state.winner
#debug "Growing leaf: " + self.to_s
for i in 0..6
if @state.canPlay i then
childState = @state.deep_copy
childState.play i
child = Node.new(childState, @player)
children[i] = child
end
end
@isLeaf = false
else
for child in @children.values
child.grow
end
end
end
def findNodeWithState( state )
if state.lastPlayed then
return @children[state.lastPlayed]
else
return nil
end
end
def to_s
return "Played: " + @state.lastPlayed.to_s + " Points: " + totalPoints.to_s
end
end
class AIPlayer
def initialize( level, name )
@level = level
@name = name
end
def to_s
return @name + " (" + @level.to_s + ")"
end
def selectBestNode
# Add some randomness
bestChild = nil
bestChildCount = nil
for child in @node.children.values
#puts child.state
#puts child.totalPoints
if !bestChild then
bestChild = child
bestChildCount = 1
else
if child.totalPoints > bestChild.totalPoints then
bestChild = child
bestChildCount = 1
elsif child.totalPoints == bestChild.totalPoints then
bestChildCount = bestChildCount + 1
if rand(bestChildCount) == 0 then
bestChild = child
end
end
end
end
#Just to make sure
if !bestChild then
raise "bestChild is nil"
end
debug "Best points: " + bestChild.totalPoints.to_s
@node = bestChild
end
def play(state)
if state.lastPlayed then
debug "Finding last played node"
@node = @node.findNodeWithState(state)
@node.grow
end
debug "Finding the best node"
selectBestNode
@node.grow
state.play @node.state.lastPlayed
end
def setupGame(state, player)
@node = Node.new(state, player)
debug "Creating min max tree (" + (7**@level).to_s + " nodes)..."
(1..@level).each{ @node.grow }
end
end
class HumanPlayer
def initialize(name)
@name = name
end
def to_s
return @name
end
def play(state)
puts @name + ", make your move:"
begin
toPlay = gets
if toPlay == "q\n" then
exit
end
toPlay = toPlay.to_i
if !state.canPlay toPlay
puts "Can't play " + toPlay.to_s + ". Select another:"
selectOther = true
else
state.play toPlay
end
end while selectOther
end
def setupGame(state, player)
end
end
def runGame
puts "Run against ai (A), another player (P) or let two AIs play against eachother (X)?"
gameType = readline.strip
case gameType
when "A", "a"
player1 = createAIPlayer
player2 = createHumanPlayer
when "P", "p"
player1 = createHumanPlayer
player2 = createHumanPlayer
when "X", "x"
player1 = createAIPlayer
player2 = createAIPlayer
else
puts "Invalid input: #{gameType}"
exit
end
players = [player1, player2]
state = State.new
player1.setupGame(state, State::Player1)
player2.setupGame(state, State::Player2)
while (!state.winner && !state.isFull)
for player in players
puts state
player.play(state)
puts player.to_s + " played: " + state.lastPlayed.to_s
if state.winner then break end
end
end
if state.winner
puts state
puts "Winner: " + state.winner.to_s
elsif state.isFull
puts state
puts "Draw!"
end
end
$aiCounter = 0
def createAIPlayer
$aiCounter = $aiCounter + 1
name = "AI " + $aiCounter.to_s
puts "Enter " + name + " level (1 to 5):"
level = readline.to_i
return AIPlayer.new(level, name)
end
$humanCounter = 0
def createHumanPlayer
$humanCounter = $humanCounter + 1
defaultName = "Human " + $humanCounter.to_s
puts "Enter name of human player (default " + defaultName + "):"
name = readline.strip
if !name || name == "" then
name = defaultName
end
return HumanPlayer.new(name)
end
def runTests
state = State.new
state.play(3)
state.play(3)
state.play(4)
state.play(4)
state.play(5)
state.play(5)
state.play(6)
#test getPlayed
if state.getPlayed([3, 0]) != State::Player1 then raise "getPlayed doesn't work" end
if state.getPlayed([3, 1]) != State::Player2 then raise "getPlayed doesn't work" end
if state.getPlayed([3, 2]) != 1 then raise "getPlayed doesn't work" end
if state.getPlayed([3, 2]).class != Fixnum then raise "getPlayed doesn't work" end
#test findWinner
winningRow = (3..6).collect{|c| [c, 0]}
if !state.findWinner(winningRow) then raise "findWinner doesn't work. winningRow=" + winningRow.to_s end
#test state.winner
if state.winner == nil then raise "winner should be set" end
puts "All tests ok"
end
runGame
#runTests
Monday, February 2, 2009
BDD using NBehave + Rhino Mocks AMC
Update: I found an old blog post by Aslak Hellesøy (the main developer behind Cucumber) that touches on this subject.
Some time ago, I investigated what BDD is all about. In essence, it's TDD with a twist. For example, the word "test" implies that we're testing what someone (we?) already made, but TDD says we're going to write the tests before the actual implementation of the unit of code. Somewhat, the word "test" has a direction backwards, while "should" has a direction forward. Hence, "should" is more comprehensive to use when describing and specifying the future. Makes sense?
What I'd like to show you is a piece of code I wrote to see how NBehave's story runner could work with Rhino Mocks' Auto Mocking Container[1, 2].
Now a question pops up: since we have only specified and tested the first (top-level) interaction, what about the rest of the interactions? I think this is a good question that leads us further down the rabbit hole.
A written user story comes from a dialogue with a person with domain knowledge. Hopefully, after some discussion, we have understood some of the moving parts of the domain problem the customer wants us to solve. Let's assume that we want to implement a single feature at a time, a couple of questions arise: should we start top-down or bottom-up? And how far "up" should we go, i.e. should we start with the UI or the domain model, if we choose a top-down approach?
If we choose to start with the domain model, then I think the above way of specifying the behavior looks nice. The key question is where the classes in the story come from originally. I have no easy answer for that. Of course they should originate from the domain problem, but how? "The model is the code - the code is the model", but it probably takes a while to "get it right". Maybe code like the above could help us to see if we have understood the problem in the first place?
Now back to the question: "what about the rest of the interactions"? We have ensured that the class which is in "the center" of the particular interaction chain (the player turn) lives in a faked world (a small board and a player near go) and we finally assert that when something happens (player passes 'GO') then some state has changed (the player gets money). The nice thing is that we now know more about what functionality the dependent classes should provide. For example, IBoard needs to have a method GetIndexForPlayer and if there is a class implementing that interface, then a NotImplementedException is probably thrown from that method, in order to compile. Next step could be to start thinking on that particular method and choose to either write a mocked unit test or an "ordinary" unit test.
Of course, real acceptance tests are also needed, but the purpose and scope of those tests are quite different. At least that's what I think.
What do you think?
Some time ago, I investigated what BDD is all about. In essence, it's TDD with a twist. For example, the word "test" implies that we're testing what someone (we?) already made, but TDD says we're going to write the tests before the actual implementation of the unit of code. Somewhat, the word "test" has a direction backwards, while "should" has a direction forward. Hence, "should" is more comprehensive to use when describing and specifying the future. Makes sense?
What I'd like to show you is a piece of code I wrote to see how NBehave's story runner could work with Rhino Mocks' Auto Mocking Container[1, 2].
[Story, Test]When this test is run with ReSharper, the test passes and outputs the story with indentation. Nice! (Except the "mockery has started" part of the story..)
public void GetMoneyWhenPassGO()
{
// Set up and initialize
var mocks = new MockRepository();
var container = new Rhino.Testing.AutoMocking.AutoMockingContainer(mocks);
container.Initialize();
// Resolve and obtain references
IPlayerTurn turn = container.Create<PlayerTurn>();
IBoard board = container.Resolve<IBoard>();
IPlayer player = container.Resolve<IPlayer>();
turn.AddPlayers(new List<Player>() {player});
// Story begins here
var story = new Story("Player recieves money when passes 'GO'");
story
.AsA("Player")
.IWant("to recieve money when I pass 'GO'")
.SoThat("I can buy things that generate money");
story
.WithScenario("Normal play scenario")
.Given("A board with 4 squares", () => Expect.Call(board.NumberOfSquares).Return(4))
.And("a player near 'GO'", () => Expect.Call(board.GetIndexForPlayer(player)).Return(2))
.And("mockery has started", () => mocks.ReplayAll())
.When("player passes 'GO'",() => turn.PlayerSequence(player, 3))
.Then("the player earns $4000", () => player.AssertWasCalled(x => x.Credit(4000)));
}
Now a question pops up: since we have only specified and tested the first (top-level) interaction, what about the rest of the interactions? I think this is a good question that leads us further down the rabbit hole.
A written user story comes from a dialogue with a person with domain knowledge. Hopefully, after some discussion, we have understood some of the moving parts of the domain problem the customer wants us to solve. Let's assume that we want to implement a single feature at a time, a couple of questions arise: should we start top-down or bottom-up? And how far "up" should we go, i.e. should we start with the UI or the domain model, if we choose a top-down approach?
If we choose to start with the domain model, then I think the above way of specifying the behavior looks nice. The key question is where the classes in the story come from originally. I have no easy answer for that. Of course they should originate from the domain problem, but how? "The model is the code - the code is the model", but it probably takes a while to "get it right". Maybe code like the above could help us to see if we have understood the problem in the first place?
Now back to the question: "what about the rest of the interactions"? We have ensured that the class which is in "the center" of the particular interaction chain (the player turn) lives in a faked world (a small board and a player near go) and we finally assert that when something happens (player passes 'GO') then some state has changed (the player gets money). The nice thing is that we now know more about what functionality the dependent classes should provide. For example, IBoard needs to have a method GetIndexForPlayer and if there is a class implementing that interface, then a NotImplementedException is probably thrown from that method, in order to compile. Next step could be to start thinking on that particular method and choose to either write a mocked unit test or an "ordinary" unit test.
Of course, real acceptance tests are also needed, but the purpose and scope of those tests are quite different. At least that's what I think.
What do you think?
Friday, January 16, 2009
The small things: Fisher Space Pen

I got this pen from my girlfriend as a christmas gift. It's a Fisher Space Pen and I'm very happy for it!
I believe that it's really worth investing in the cheap stuff you use daily, like pen and paper (though, in this case my girlfriend did the investment, but that's another story). Of course, that's assuming that you use pen and paper. You really should - pen and paper are great tools!
Monday, December 8, 2008
PomodoroButtButtButt
Øredev was a fantastic conference! I can't stress that enough! So why haven't I blogged about it? Well, there's so many blogs already about it (google on "øredev" and "blog") so I don't really know how to contribute more content, just repeat what's already been said. That's why.
Instead, I'm going to write a note on one thing that I've taken with me from a talk at Øredev: the Pomodoro Technique. It's essentially a technique that takes agile to the personal productivity level: working in small and timeboxed iterations (25 minutes), with short breaks (3-5 minutes) between each iteration and longer breaks (15-30 minutes) between 4 iterations in a row. Oh, by the way, an iteration is called a pomodoro, italian for tomato. Why tomato? Because the inventor of the Pomodoro Technique, Francesco Cirillo, used an egg timer formed as a tomato during the early phase developing the technique. Further, each day starts with planning and ends with collecting and visualizing the data collected, ready to be analysed and retrospected.
So, the idea is very simple, but of course there a lot more to it. What you should start with is to read Staffan Nöteberg's Pomodoro Technique in 5 minutes. Actually, when the videos from Øredev get published, you should start there: Staffan Nöteberg did an excellent talk on the Pomodoro Technique, sometimes using hats and dolls to illustrate his points.
There's also a quite large pdf by Francesco Cirillo available, but I haven't had time to read that one yet.
I've just tried out the Pomodoro Technique myself for a couple of days now and some days have contained more pomodoros than others. Basically, I bought an egg timer for 25 SEK (around $3) and started with the fixed timebox part of the technique and logged the results. The second day I started to do some naïve estimation for each task. I also started with post-it notes for tasks, my personal pull system.
If you follow and read the links in this post, you'll see that I don't really do that much of the Pomodoro Technique! That's ok with me, I'm aware of that and that's why the title of this post is "PomodoroButtButtButt" (paraphrasing Jeff Sutherland's ScrumButt). I'm just getting used to the habit though, and making the human beings around me used to it as well. No need to be extreme here..
By the way, I'm still recording my workday in TimeSnapper, now TimeSnapper Professional. But that's a future blog post.
Instead, I'm going to write a note on one thing that I've taken with me from a talk at Øredev: the Pomodoro Technique. It's essentially a technique that takes agile to the personal productivity level: working in small and timeboxed iterations (25 minutes), with short breaks (3-5 minutes) between each iteration and longer breaks (15-30 minutes) between 4 iterations in a row. Oh, by the way, an iteration is called a pomodoro, italian for tomato. Why tomato? Because the inventor of the Pomodoro Technique, Francesco Cirillo, used an egg timer formed as a tomato during the early phase developing the technique. Further, each day starts with planning and ends with collecting and visualizing the data collected, ready to be analysed and retrospected.
So, the idea is very simple, but of course there a lot more to it. What you should start with is to read Staffan Nöteberg's Pomodoro Technique in 5 minutes. Actually, when the videos from Øredev get published, you should start there: Staffan Nöteberg did an excellent talk on the Pomodoro Technique, sometimes using hats and dolls to illustrate his points.
There's also a quite large pdf by Francesco Cirillo available, but I haven't had time to read that one yet.
I've just tried out the Pomodoro Technique myself for a couple of days now and some days have contained more pomodoros than others. Basically, I bought an egg timer for 25 SEK (around $3) and started with the fixed timebox part of the technique and logged the results. The second day I started to do some naïve estimation for each task. I also started with post-it notes for tasks, my personal pull system.
If you follow and read the links in this post, you'll see that I don't really do that much of the Pomodoro Technique! That's ok with me, I'm aware of that and that's why the title of this post is "PomodoroButtButtButt" (paraphrasing Jeff Sutherland's ScrumButt). I'm just getting used to the habit though, and making the human beings around me used to it as well. No need to be extreme here..
By the way, I'm still recording my workday in TimeSnapper, now TimeSnapper Professional. But that's a future blog post.
Thursday, November 13, 2008
TimeSnapper against MultiTasking
I have been working at Dotway now, for almost two weeks. When your environment change, there's a good opportunity for changing habits as well. So, I started with the habit of using TimeSnapper every morning. TimeSnapper is a tool that takes a screenshot every 5 seconds or so, and has the ability to "play" the images, as a movie. The movie obviously has a higher image frequency than 5 seconds, so a whole day takes approximately 5-10 minutes to play.
Essentially, you gain the ability to self-monitor - seeing yourself in third person. Early and frequent feedback is a really good thing to have in most areas, like TDD for development or Scrum for projects. In my opinion, TimeSnapper gives the same kind of early and frequent feedback. So, every morning I play the movie of yesterday, write down the activities in time intervals, analyse my behavior, and ask myself the question "What should I do today that make my morning analysis more joyful tomorrow?". Let me explain..
I don't like when I'm forced to write: "08:00-11:00, XX:ed, YY:ed and ZZ:ed" - that's not really informative, i.e., how much time did I spent on XX, compared to YY? But it's not the logging problem in itself that I have problems with, it's that I know that it's bad for productivity to multitask, but still I do it. Without knowing it as well, it seems. Constantly context switching is bad for productivity. So, I should only focus on one task simultaneously to make tomorrow morning a good start at the day.
Look, if you're using GTD (a nice time management methodology), but instead of doing something useful instead read LifeHacker (a nice site/blog) every 10th minute, something is utterly wrong! Not really getting things done, are you? Though, it can be hard to see for yourself. TimeSnapper lets you visualize your behaviour at the computer, putting your (potentially) multi-tasking in an embarrasingly bright light to yourself.
Thanks to Scott Hanselman for making the tools list where I found TimeSnapper.
As a side note, I really like 43folders' new direction. Or, at least, this particular post.
I don't like when I'm forced to write: "08:00-11:00, XX:ed, YY:ed and ZZ:ed" - that's not really informative, i.e., how much time did I spent on XX, compared to YY? But it's not the logging problem in itself that I have problems with, it's that I know that it's bad for productivity to multitask, but still I do it. Without knowing it as well, it seems. Constantly context switching is bad for productivity. So, I should only focus on one task simultaneously to make tomorrow morning a good start at the day.
Look, if you're using GTD (a nice time management methodology), but instead of doing something useful instead read LifeHacker (a nice site/blog) every 10th minute, something is utterly wrong! Not really getting things done, are you? Though, it can be hard to see for yourself. TimeSnapper lets you visualize your behaviour at the computer, putting your (potentially) multi-tasking in an embarrasingly bright light to yourself.
Thanks to Scott Hanselman for making the tools list where I found TimeSnapper.
As a side note, I really like 43folders' new direction. Or, at least, this particular post.
Thursday, October 30, 2008
Turtle Graphics :: The big refactoring
Last time on "Turtle Graphics", we ended up having the type Turtle -> [Turtle] on functions. The combine function had the type [Turtle] -> (Turtle -> [Turtle]) - Turtle. Let's have some "fun"!
First, we add a helpful parameter to the turtle - penIsDown, i.e., the turtle is writing.
We then add two useful functions for pen modification:
Second, we assume that it would be useful to split the functionality of returning a value and log, pretty much following separation of concerns. We could do this in a tuple, but I prefer having names on things:
This has some implications on our code. All the "core" functions must now return both a turtle value and a singleton log. Oh, and by the way, the Command type changed as well.
We must also change the function for combining functions:
As you see, there's a lot of duplicate code. Let's do an ExtractMethod (sort of):
Still, we could be more generic in our logging type. That is, there is still a restriction on that the value returned and the log have the same type: the log is a list of the same type as the value has. We try to relax this restriction:
Maybe we did too much, logs isn't a list anymore. However, if it's really necessary, we'll find out through type inference. It's not obvious that we really need a list, just something we can append "stuff" to. Anyway, we get some compiler errors now:
`Logged Turtle' is not applied to enough type arguments Expected kind `?', but `Logged Turtle' has kind `k -> *' In the type synonym declaration for `Command'
We "fix" this by removing the Command type synonym and all references to it. I have a feeling that we'll need to fiddle some more with the types, so right now they're only in the way. If the types really are needed, we will find out (by a compiler error)! Though, it could be interesting to see what the type of e.g., "go" is:
Ah, just what I expected, but was too lazy too write. ;) Let's check the combining function:
Hmm, this is rather weird! Before, the function was strongly bound to the Turtle type, which doesn't seem to be the case anymore. Moreover, we see that the input value type (v) doesn't need to be the same as the output value type (v1). How cool is that!?! It would be hard for me to look at the function and calculate the type myself, but Haskell just inferred the most generic type it could find. Coolness!
As always, a design pattern can be hard to spot, especially if you haven't spotted it before. Here's how Gregg Irwin puts it (from an Øredev presentation by Jimmy Nilsson):
Let's try to instantiate the monad class:
We get a compiler error:
We try to remove both type parameters:
..but still an error (yet, another one)
As you might see, we need to bind one of the types, whereas the other one needs to be "free". This puts us in a dilemma, since we know that we have both a type "v" and "v1". Thus, the type of the log must be bound (or, at least given a parametrized name):
So Logged is missing out one type parameter. It's kind of a function over types, that takes a type and returns another type - just as the error message above implied. Though, we get an error again when we try to implement bind:
Now, we actually need to say that the log is a list. Maybe we can remove this requirement in a later blog post, but right now we go with the compiler.
Hey, it works! Or, at least it compiles. But that tends to be synonyms in Haskell ;) We specify "return":
Notice that we can still use |>| as usual:
So, why all this trouble? Well, it wasn't that hard! Essentially, all we did was to make the logging a bit more separated and generic. Then we adjusted the types a bit to make them align with Haskell's monad class. The big win is that our Logger is now reusable if we want to log something else than turtles in the future. So, by adjusting towards a common pattern, we gained both syntactic sugar and reusability.
Of course, there are some ways to improve. I'll perhaps cover this in future posts. Oh, and by the way, our Logger monad is actually the Writer monad. Just thought you should know that.. ;)
Conclusion: Brian Beckman was right, we've invented monads by ourselves, maybe without thinking about it. Or?
Note: Since I'm not a master in category theory, I'm not sure if Logger actually was a "real" monad (strictly speaking), before we changed the order of the type parameters and removed a type parameter in the monad instantiation, making it have the right kind. Any ideas?
First, we add a helpful parameter to the turtle - penIsDown, i.e., the turtle is writing.
data Turtle = Turtle
x :: Double,
y :: Double,
alpha :: Double, -- alpha = 0 means East
penIsDown :: Bool
}
deriving (Show)
We then add two useful functions for pen modification:
penDown t = let t' = t {penIsDown = True} in Logged {value = t', logs = [t']}
penUp t = let t' = t {penIsDown = False} in Logged {value = t', logs = [t']}
Second, we assume that it would be useful to split the functionality of returning a value and log, pretty much following separation of concerns. We could do this in a tuple, but I prefer having names on things:
data Logged l = Logged {
value :: l,
logs :: [l] } deriving (Show)
This has some implications on our code. All the "core" functions must now return both a turtle value and a singleton log. Oh, and by the way, the Command type changed as well.
type Command = Turtle -> Logged Turtle
go, left, right, penDown, penUp :: Command
go t = let t' = t {x = x t + step * cos (alpha t),
y = y t + step * sin (alpha t)
}
in Logged {value = t', logs = [t']}
left = rotate (pi/2)
right = rotate (-pi/2)
penDown t = let t' = t {penIsDown = True} in Logged {value = t', logs = [t']}
penUp t = let t' = t {penIsDown = False} in Logged {value = t', logs = [t']}
We must also change the function for combining functions:
(|>|) :: Logged Turtle -> Command -> Logged Turtle
logged |>| f = let logged' = f (value logged)
in Logged {value = value logged',
logs = logs logged' ++ logs logged}
As you see, there's a lot of duplicate code. Let's do an ExtractMethod (sort of):
logThis val = Logged {value = val, logs = [val]}
go, penDown, penUp :: Command
go t = logThis $ t {x = x t + step * cos (alpha t),
y = y t + step * sin (alpha t) }
penDown t = logThis $ t {penIsDown = True}
penUp t = logThis $ t {penIsDown = False}
rotate :: Double -> Command
rotate v t = logThis $ t {alpha = alpha t + v}
Still, we could be more generic in our logging type. That is, there is still a restriction on that the value returned and the log have the same type: the log is a list of the same type as the value has. We try to relax this restriction:
data Logged v l = Logged {
value :: v,
logs :: l
}
deriving (Show)
Maybe we did too much, logs isn't a list anymore. However, if it's really necessary, we'll find out through type inference. It's not obvious that we really need a list, just something we can append "stuff" to. Anyway, we get some compiler errors now:
`Logged Turtle' is not applied to enough type arguments Expected kind `?', but `Logged Turtle' has kind `k -> *' In the type synonym declaration for `Command'
We "fix" this by removing the Command type synonym and all references to it. I have a feeling that we'll need to fiddle some more with the types, so right now they're only in the way. If the types really are needed, we will find out (by a compiler error)! Though, it could be interesting to see what the type of e.g., "go" is:
*Main> :t go
go :: Turtle -> Logged Turtle [Turtle]
Ah, just what I expected, but was too lazy too write. ;) Let's check the combining function:
*Main> :t (|>|)
(|>|) :: Logged v [a] -> (v -> Logged v1 [a]) -> Logged v1 [a]
Hmm, this is rather weird! Before, the function was strongly bound to the Turtle type, which doesn't seem to be the case anymore. Moreover, we see that the input value type (v) doesn't need to be the same as the output value type (v1). How cool is that!?! It would be hard for me to look at the function and calculate the type myself, but Haskell just inferred the most generic type it could find. Coolness!
As always, a design pattern can be hard to spot, especially if you haven't spotted it before. Here's how Gregg Irwin puts it (from an Øredev presentation by Jimmy Nilsson):
1. You use it without being aware that you’re using itEssentially, our Logger type is a monad. Or, actually, the type of |>| resembles >>=, which is the associative function that composes a particular monad. Since monads are important in Haskell, some syntactic sugar (the do-notation) has been added to make it easier to work with them.
2. You hear about it, read up on it, and tinker a bit
3. You learn more and start using it explicitly, if naively
4. You get the fire and evangelize (optional)
5. Something ”clicks”
6. You learn more and apply it ”less naively”and more implicitly
7. Time passes and you see flaws
8. You question the concept (often because you misapplied it)
9. You either forget about it or add knowledge and experience
(Repeat steps 5-9 if necessary)
10. You use it without being aware that you are using it
Let's try to instantiate the monad class:
instance Monad (Logged a b) whereWe get a compiler error:
Kind mis-match
Expected kind `* -> *', but `Logged a b' has kind `*'
In the instance declaration for `Monad (Logged a b)'
We try to remove both type parameters:
instance Monad (Logged) where..but still an error (yet, another one)
`Logged' is not applied to enough type arguments
Expected kind `* -> *', but `Logged' has kind `* -> * -> *'
In the instance declaration for `Monad (Logged)'
As you might see, we need to bind one of the types, whereas the other one needs to be "free". This puts us in a dilemma, since we know that we have both a type "v" and "v1". Thus, the type of the log must be bound (or, at least given a parametrized name):
data Logged l v = Logged { --notice the different order
value :: v,
logs :: l
}
deriving (Show)
instance Monad (Logged l) where
So Logged is missing out one type parameter. It's kind of a function over types, that takes a type and returns another type - just as the error message above implied. Though, we get an error again when we try to implement bind:
instance Monad (Logged l) where l >>= f = l |>| f
Couldn't match expected type `[a]' against inferred type `l' (a rigid variable)
`l' is bound by the instance declaration at writer5.hs:46:0
Expected type: Logged [a] v
Inferred type: Logged l a1
In the first argument of `(|>|)', namely `l'
In the expression: l |>| f
Now, we actually need to say that the log is a list. Maybe we can remove this requirement in a later blog post, but right now we go with the compiler.
data Logged l v = Logged {
value :: v,
logs :: [l]
}
deriving (Show)
Hey, it works! Or, at least it compiles. But that tends to be synonyms in Haskell ;) We specify "return":
instance Monad (Logged l)
where l >>= f = l |>| f
return val = Logged {value = val, logs = []}
Notice that we can still use |>| as usual:
*Main> start |>| go |>| go
Logged {value = Turtle {x = 2.0, y = 0.0, alpha = 0.0, penIsDown = True},
logs = [Turtle {x = 2.0, y = 0.0, alpha = 0.0, penIsDown = True},
Turtle {x = 1.0, y = 0.0, alpha = 0.0, penIsDown = True},
Turtle {x = 0.0, y = 0.0, alpha = 0.0, penIsDown = True}]}
So, why all this trouble? Well, it wasn't that hard! Essentially, all we did was to make the logging a bit more separated and generic. Then we adjusted the types a bit to make them align with Haskell's monad class. The big win is that our Logger is now reusable if we want to log something else than turtles in the future. So, by adjusting towards a common pattern, we gained both syntactic sugar and reusability.
Of course, there are some ways to improve. I'll perhaps cover this in future posts. Oh, and by the way, our Logger monad is actually the Writer monad. Just thought you should know that.. ;)
Conclusion: Brian Beckman was right, we've invented monads by ourselves, maybe without thinking about it. Or?
Note: Since I'm not a master in category theory, I'm not sure if Logger actually was a "real" monad (strictly speaking), before we changed the order of the type parameters and removed a type parameter in the monad instantiation, making it have the right kind. Any ideas?
Tuesday, October 28, 2008
My first F#, Binary Chop
Yesterday, I really felt like trying out F#. To get some inspiration, I visited PragProgs katas, and chose Kata Two -- Karate Chop. Or, actually, I just implemented a "functional" solution. I tried to make an imperative pointer-based solution (which I might post later, when I have resolved a strange bug). Anyway, I had never coded F# before, so there might be a few places where I could have e.g. chosen a library function instead of implementing it myself. If you have any suggestions or general comments, please post them!
By the way, is there any way to program in literate F#?
I will definitly be posting more F# posts in the future!
Cheers
By the way, is there any way to program in literate F#?
#lightFirst, a few helper functions for triples.let fst3 (a,b,c) = aDefine the middle index, for simplicity return 0 if list is empty.
let snd3 (a,b,c) = b
let trd3 (a,b,c) = c
let middleIndex xs = if List.is_empty xs then 0 else (List.length xs - 1)/2Define a function that returns the middle element of a list, and two functions that returns the first/last remaining halfs. Note that there might not be a middle element, so we use the option type.let firstHalf xs = Seq.take (middleIndex xs) xsLet us group the functions in a convenient triple.
let middleElem xs =
match (xs) with
| [] -> None
| xs -> Some (xs.Item (middleIndex xs))
let lastHalf xs =
match xs with
| [] -> Seq.empty
| xs2 -> Seq.skip (middleIndex xs + 1) xs2
let splitInHalf xs = (firstHalf xs, middleElem xs, lastHalf xs)Now, define a recursive function that 1) splits the list in three parts 2) reuse some definitions 3) return "None" if middle is empty 4) otherwise we can test the middle for equality, if equal then return the current index 5) if not equal, choose appropriate half and recurse.let rec exists x xs i =This is the function a user would call.
let triple = splitInHalf xs in //1
let maybeMiddle = snd3 triple //2
let firstPart = Seq.to_list (fst3 triple)
let lastPart = Seq.to_list (trd3 triple)
if Option.is_none maybeMiddle then None //3
else let middle = Option.get maybeMiddle in //4
if x.Equals middle then Some(i) //5
elif middle > x then exists x firstPart (middleIndex firstPart)
else exists x lastPart ((i+1) + middleIndex lastPart)
let public ex x xs = exists x xs (middleIndex xs)Some tests, just to check, plus a helper function for equality over options.//TestsNow, I must say that I had a real good time developing this! Ok, some minor things didn't went as smoothly as I'd hope for, but it was actually the first time that I tried F#. I've never had such a good experience with a language the first day of use.
let eq x y = if Option.is_none x then Option.is_none y else x.Equals y
let res = [
ex 3 [];
ex 3 [1];
ex 1 [1];
ex 1 [1;3;5];
ex 3 [1;3;5];
ex 5 [1;3;5];
ex 0 [1;3;5];
ex 2 [1;3;5];
ex 4 [1;3;5];
ex 6 [1;3;5];
ex 1 [1;3;5;7];
ex 3 [1;3;5;7];
ex 5 [1;3;5;7];
ex 7 [1;3;5;7];
ex 0 [1;3;5;7];
ex 2 [1;3;5;7];
ex 4 [1;3;5;7];
ex 6 [1;3;5;7];
ex 8 [1;3;5;7];
]
let answers = [None; None; Some 0;
Some 0; Some 1; Some 2; None; None; None; None;
Some 0; Some 1; Some 2; Some 3; None; None; None; None; None
]
let asserts = Seq.for_all2 eq res answers
asserts
I will definitly be posting more F# posts in the future!
Cheers
Wednesday, October 22, 2008
Category Theory
Guess what landed on my hallway floor today: "Basic Category Theory for Computer Scientists". Thank you Mr Mailman!

There's a lot of "greek" in there! Hopefully, I'll decipher it (and understand it, of course).
There's a lot of "greek" in there! Hopefully, I'll decipher it (and understand it, of course).
Tuesday, October 21, 2008
CoachTV
In the middle of August, David Heinemeier Hansson twittered this:
I think it's hard to analyze yourself from the outside. Reminds me of a quote of Richard Feynman, the 1965 Nobel prize winner in physics:
Note: I actually wrote this post before watching episode #26 of CoachTV, where Lars asks the viewers to "tell our friends" about his show. Just thought you should know that.. :)
Lars Pind is doing video coaching: http://coachtvblog.com/?p=3 -- good thoughts on probability and significance. 4:59 PM Aug 16thSince that date, I have been following Lars Pind's fantastic video blog, CoachTV.
I think it's hard to analyze yourself from the outside. Reminds me of a quote of Richard Feynman, the 1965 Nobel prize winner in physics:
"The first principle is that you must not fool yourself—and you are the easiest person to fool."It's hard to summarize what Pind's message is, so I rather not try. Instead, I want to re-post a comment that I did on one of his episodes. What triggered me to post the comment was that Pind talked about eating and that the next time the viewer ate something, he/she should try to really look at the food, feel the texture, slowly swallow, feel the taste, etc, etc. You get the picture? Obviously, the overall "taste experience" is not only about always eating good food, but rather that it is up to you, if you bother to enjoy it or not. Made me think about music:
Lars, you said that when we eat or drink something, we should try to feel the taste and texture more. That reminded me of the composer John Cage, who had the same opinion about sound. His most famous piece is “4′33″, which is 4 minutes and 33 seconds of silence, written for piano. In summary, Cage had the opinion that there’s music everywhere, but it’s up to us to listen to it. So, even rush hour traffic can be music. Or when it’s so quiet that you can hear our own blood flow and pulse.Could it be that the same reasoning goes for your other sensations and feelings as well? If not, why?
It’s up to ourselves to broaden our senses and perspectives, so that we can enjoy the music in our everyday life, also when sound is not involved per se.
Note: I actually wrote this post before watching episode #26 of CoachTV, where Lars asks the viewers to "tell our friends" about his show. Just thought you should know that.. :)
Monday, October 20, 2008
Podcast: Herding Code
There is a fairly new (May 2008) podcast that I listened to a lot lately (including their old episodes): Herding Code. These episodes are particularly nice:
Enjoy :)
Enjoy :)
Sunday, October 19, 2008
TDD, reflection and the PropertiesEqual extension method
In my last post I wrote about the extension method ForEach, which is a very simple but useful method, at least when it comes to readability.
In this post I'll try to explain another extension method, which I'll call PropertiesEqual. It's purpose is to extend the object class with a method to compare the properties of two objects:
You probably know of the object.Equals method, which per default compares the memory addresses of two objects. That is, two objects are equal only if they are exactly the same object. If you really want to compare the content of two objects, you need to override this function in your class and manually compare them.
When I designed this function, I started with two simple test cases:
1. If two objects of the same class have the same public properties, yield true
2. If two objects of the same class have different public properties, yield false
Translated to code, this becomes:
The implementation is very straight forward:
typeof(T).GetProperties() will return all public properties of T, and property.GetValue(obj, null) will return the value of a given property. The All extension method returns true only if all elements of the sequence satisfy the given condition, i.e. all properties are equal.
The test cases will pass fine, and we now have a simple way of comparing properties of two objects! In the next post I'll try to describe how to extend the method with support for recursive properties (compare properties of a property), and in the one after that I'll write about how to implement an IEqualityComparer based on this method.
EDIT: Note, these series aren't much of the type "here is a revolutionary new technique", but more of "here is how I would write the code for this". My focus is to get you to understand how I think when I design methods, not to tell you that "this is the way"!
In this post I'll try to explain another extension method, which I'll call PropertiesEqual. It's purpose is to extend the object class with a method to compare the properties of two objects:
public static bool PropertiesEqual<T>(this T obj1, T obj2)
{
return true if all properties of obj1 equals all properties of obj2
}
You probably know of the object.Equals method, which per default compares the memory addresses of two objects. That is, two objects are equal only if they are exactly the same object. If you really want to compare the content of two objects, you need to override this function in your class and manually compare them.
When I designed this function, I started with two simple test cases:
1. If two objects of the same class have the same public properties, yield true
2. If two objects of the same class have different public properties, yield false
Translated to code, this becomes:
class TestClass
{
public int A { get; set; }
public int B { get; set; }
}
[TestMethod()]
public void PropertiesEqualTest()
{
Assert.IsTrue(new Test { A = 1, B = 1 }.PropertiesEqual(new Test { A = 1, B = 1 }));
Assert.IsFalse(new Test { A = 1, B = 1 }.PropertiesEqual(new Test { A = 1, B = 0 }));
}
The implementation is very straight forward:
public static bool PropertiesEqual<T>(this T obj1, T obj2)
{
return typeof(T).GetProperties().All(property =>
{
var prop1 = property.GetValue(obj1, null);
var prop2 = property.GetValue(obj2, null);
return prop1.EqualsTo(prop2);
});
}
typeof(T).GetProperties() will return all public properties of T, and property.GetValue(obj, null) will return the value of a given property. The All extension method returns true only if all elements of the sequence satisfy the given condition, i.e. all properties are equal.
The test cases will pass fine, and we now have a simple way of comparing properties of two objects! In the next post I'll try to describe how to extend the method with support for recursive properties (compare properties of a property), and in the one after that I'll write about how to implement an IEqualityComparer based on this method.
EDIT: Note, these series aren't much of the type "here is a revolutionary new technique", but more of "here is how I would write the code for this". My focus is to get you to understand how I think when I design methods, not to tell you that "this is the way"!
Code Kata : Monopoly
Yesterday evening, me and two other friends arranged a highly spontaneus and inofficial code kata, at my friend's apartment. The task was to develop a Monopoly game, using TDD. It was sort of an experiment as well, we wanted to see how TDD could help us discovering design, rather than inventing it.
We started by talking about the domain, listing some words that we thought were important to the game. Then we made a small domain model diagram, just with boxes and lines (the relations had no directions or multiplicities). This was fun! It felt like we were back in school again.. :)
After that, we started to make some user stories, each on a small piece of paper. Here are the stories we came up with (in prioritized order):
An interesting detail is that we kind of get stuck on the "the dices show" part of the first story. It's obviously something that has to do with random number(s), but how should we test that? I.e., we thought that only players would need dices, but if a player use the Random() system method, then we must capture it in a public state in order to know if the player actually walked the number of steps that the dices show. Not nice! We felt the urge to really talk about this, to see if logical arguments could lead us into a good, and hopefully pragmatic, solution to this problem. We ended up with dependency injecting an "IDice" - something that could give us a random number between two and twelwe, and mocking the IDice in the test. Nice! Now we could manipulate the player through fake dices, without having code smells all over the place!
Though, in retrospective, it would have been nice with an expert on TDD in the room. In the end, you would like yourself (or the group) to ask good questions and answer them logically, but without experience, asking the right questions in the right time is hard. A teacher behind the back, mentoring and supporting would be nice to have. Reminds me a little about Polya, "How to Solve It". Though, doing the excercise without a "master" was probably a good idea, in some way: it made us (more) convinced about what we were doing, and if we weren't convinced, we had to talk about it.
We did the excercise for about six hours, but we had dinner and wine during that time as well, and perhaps we weren't that effective all the time :) Anyway, we implemented all the stories, except the last one (a half-baked story).
Thank you for a very nice evening!
We started by talking about the domain, listing some words that we thought were important to the game. Then we made a small domain model diagram, just with boxes and lines (the relations had no directions or multiplicities). This was fun! It felt like we were back in school again.. :)
After that, we started to make some user stories, each on a small piece of paper. Here are the stories we came up with (in prioritized order):
- A player walks the number of steps the dices show.
- In the beginning of the game, the ordering of player moves is determined.
- Players act in the predetermined order (was later removed, redundant with previous).
- A player hits or passes "Go" and earn 4000.
- A player buys the street he/she is on.
An interesting detail is that we kind of get stuck on the "the dices show" part of the first story. It's obviously something that has to do with random number(s), but how should we test that? I.e., we thought that only players would need dices, but if a player use the Random() system method, then we must capture it in a public state in order to know if the player actually walked the number of steps that the dices show. Not nice! We felt the urge to really talk about this, to see if logical arguments could lead us into a good, and hopefully pragmatic, solution to this problem. We ended up with dependency injecting an "IDice" - something that could give us a random number between two and twelwe, and mocking the IDice in the test. Nice! Now we could manipulate the player through fake dices, without having code smells all over the place!
Though, in retrospective, it would have been nice with an expert on TDD in the room. In the end, you would like yourself (or the group) to ask good questions and answer them logically, but without experience, asking the right questions in the right time is hard. A teacher behind the back, mentoring and supporting would be nice to have. Reminds me a little about Polya, "How to Solve It". Though, doing the excercise without a "master" was probably a good idea, in some way: it made us (more) convinced about what we were doing, and if we weren't convinced, we had to talk about it.
We did the excercise for about six hours, but we had dinner and wine during that time as well, and perhaps we weren't that effective all the time :) Anyway, we implemented all the stories, except the last one (a half-baked story).
Thank you for a very nice evening!
Subscribe to:
Posts (Atom)