Coding Dojo #12: F#
In our latest coding dojo we worked on trying to port some of the functionality of some C# 1.0 brain models, and in particular one around simulating chaos behaviour, that Dave worked on at university.
This was more of an experimental dojo since everyone was fairly new to F# so we didn’t rotate the pair at the keyboard as frequently as possible.
What We Learnt
- The aim of the session was to try and put some unit tests around the C# code and then try and replace that code with an F# version of it piece by piece. We created an F# project in the same solution as the C# one and then managed to hook up the C# and F# projects, referencing the C# one from the F# one, with some success although the references did seem to get slightly confused at times. The support from the IDE isn't really there yet so it can be a bit tricky at times.
- We were using the XUnit.NET framework to unit test our code - this seems like a useful framework for testing F# code since it doesn't require so much setup to get a simple test working. We can just annotate a function with the 'Fact' annotation and we're good to go. One thing to be careful about is to make sure that you are actually creating functions to be evaluated by the test runner and not having the tests evaluated immediately and therefore not being picked up by the runner. For a while I had written a test similar to this and it wasn't being picked up:
] let should_do_something = Assert.AreEqual(2,2) ~~~ The type of 'should_do_something" is 'unit' and as I understand it gets evaluated immediately. What we really want to do though is create a function (with type 'unit -> unit') which can be evaluated later on: ~~~text [ ] let should_do_something() = Assert.AreEqual(2,2) ~~~ The brackets are important, something that I hadn't appreciated. We were generally running the test by directly calling the test runner from the command line - we couldn't quite work out how to hook everything up inside Visual Studio.
- I'm not sure if we went exactly to the book with our refactoring of the code to make it testable - the method on the class doing the work was private so we made it public - but it helped to get us moving. We were able to then replace this with an F# function while verifying that the output was still the same. As I mentioned on my post about the little twitter application I'm working on, I'm intrigued as to how we should structure code in F#. Apparently the answer is as objects but I'm interested how the design would differ from one done in a predominantly OO as opposed to functional language.
For next time
- I'm really enjoying playing around with F# - it's definitely interesting learning a different approach to programming than I'm used to - so we might continue working on that next time around. If not then we need to find another game to model!