Archive
F# Koans – Stock Example
At Leeds Sharp the other day, we started doing the F# Koans as a way of of trying out the language, with the aim of expanding our minds with some functional programming. A bit like coder’s LSD, if you will.
The koans are pretty good at introducing you to things, although initially it’s a bit too easy to get through them without really understanding what’s going on.
However, when you get to the stock example that all changes, as you have to actually use some of what you’ve learned to solve a more involved problem. The purpose of this post is to put up my solution in the hope of getting into a bit of a discussion with others who’ve done it, at Leeds Sharp or otherwise. I have no doubt that my implementation could be improved, so any advice would be more than welcome!
module ``about the stock example`` =
let stockData =
[ "Date,Open,High,Low,Close,Volume,Adj Close";
"2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26";
// ...
"2012-02-29,31.89,32.00,31.61,31.74,59323600,31.74"; ]
// function to split a comma-separated string into an array
let splitOnCommas (dataAsString:string) =
dataAsString.Split([|','|])
// function to take the desired parts of the array as a tuple,
// including opening-closing difference
let createPriceDifferenceTuple (fullList:string[]) =
( fullList.[0],
abs (Double.Parse(fullList.[1]) - Double.Parse(fullList.[4])) )
let maximumDifferenceTuple =
// split strings into arrays, ignoring header
List.map splitOnCommas stockData.Tail
// map arrays to tuples
|> List.map createPriceDifferenceTuple
// get maximum tuple based on second element (price difference)
|> List.maxBy snd
[<Koan>]
let YouGotTheAnswerCorrect() =
let result = fst maximumDifferenceTuple // get date, first item in tuple
AssertEquality "2012-03-13" result
Golden NuGet!
For anyone using VS2010, one tool you need to try out is NuGet (actually pronounced new-get according to Microsoft, but what do they know?!).
What is it?
NuGet is Microsoft’s answer to the much-lamented gap in the .Net space for a package management tool like Ruby’s Gems or Linux’s RPM.
NuGet simply looks after the download and installation of tools and libraries you use in your projects. It will get the appropriate version of all needed DLLs, configuration files, and related tools, put them in a folder, and do any configuration if needed. Simple! Also useful is the fact that it will download any dependencies – so for example if we want to install Shouldly, which uses Rhino Mocks, NuGet will get the appropriate version of that as well.
And that’s about it. So it won’t change your world, but it will save you a good few hours each year hunting for, downloading, and installing tools.
History
NuGet started out as NuPack, which kind of took over from the Nu open source project. Indeed, NuGet is itself open source, continuing Microsoft’s trend of a more transparent and community-involving future, which is nice.
There are other package managers for .Net, including:
However, as usual, things don’t tend to take off in the .Net community until Microsoft makes their version, which then becomes king. I haven’t tried any of those package managers, but I wouldn’t want to bet on them being too successful now NuGet’s out.
Anyway, enough of the history lesson, how do I use this thing?!
Installation
Firstly, you need to get it installed, which is simple as it’s in the Visual Studio Extension Manager (Tools -> Extension Manager). Search the Online Gallery for ‘NuGet’ and you should find it:
A couple of clicks later and you’re ready to go!
Putting it to Use
There are two interfaces. You can either right-click on a project and select ‘Add Library Reference’, and find what you need with a handy visual interface (the same as the Extension Manager):
Or, by selecting Tools -> Library Package Manager -> Package Manager Console, you can use the Powershell-based console version, like a real developer!
(Check out some NuGet Console Commands, if that’s how you want to roll.)
Either way, you’ll end up with a new ‘packages’ folder in your solution, containing the bits you need (as well as having references automatically added to your project, and configuration set):
Et voilá! You’re ready to log/unit test/mock/whatever to your heart’s content.
You can also delete packages, update packages, and so on – it’s all pretty straightforward, so I’ll leave you to work that out.
So what are you waiting for? Go and nu-get it now!! (sorry..)
Books Page
I just put up a page with a load of book reviews. It’s not finished yet but there are a fair few on there. Check it out if you’re looking for a good read!
Nice up those Assertions with Shouldly!
One thing I noticed while having a play with Ruby was that the syntax for their testing tools is quite a lot more natural-language like and easier to read – here’s an example from an RSpec tutorial:
describe User do it "should be in any roles assigned to it" do user = User.new user.assign_role("assigned role") user.should be_in_role("assigned role") endit "should NOT be in any roles not assigned to it" do user.should_not be_in_role("unassigned role") end end
Aside from the test name being a string, you can see the actual assertions in the format ‘variable.should be_some_value’, which is kind of more readable than it might be in C#:
Assert.Contains(user, unassignedRoles);
or
Assert.That(unassignedRoles.Contains(user));
Admittedly, the second example is nicer to read – the trouble with that is that you’re checking a true/false result, so the feedback you get from NUnit isn’t great:
Test ‘Access_Tests.TestAddUser’ failed: Expected: True But was: False
Fortunately, there are a few tools coming out for .net now which address this situation in a bit more of a ruby-like way. The one I’ve been using recently is Shouldly, an open source project on GitHub.
Using Shouldly (which is basically just a wrapper around NUnit and Rhino Mocks), you can go wild with should-style assertions:
age.ShouldBe(3);
family.ShouldContain(“mum”);
greetingMessage.ShouldStartWith(“Sup y’all”);
And so on. Not bad, not bad, not sure if it’s worth learning another API for though. However, the real beauty of Shouldly is what you get when an assertion fails. Instead of an NUnit-style
Expected: 3
But was: 2
- which gives you a clue, but isn’t terribly helpful – you get:
age
should be 3
but was 2
See that small but important difference? The variable name is there in the failure message, which makes working out what went wrong a fair bit easier – particularly when a test fails that you haven’t seen for a while.
Even more useful is what you get with checking calls in Rhino Mocks. Instead of calling
fileMover.AssertWasCalled(fm => fm.MoveFile(“test.txt”, “processed\\test.txt”));
and getting a rather ugly and unhelpful
Rhino.Mocks.Exceptions.ExpectationViolationException : IFileMover.MoveFile(“test.txt”, “processed\test.txt”); Expected #1, Actual #0.
With Shouldly, you call
fileMover.ShouldHaveBeenCalled(fm => fm.MoveFile(“test.txt”, “processed\\test.txt”));
and end up with
*Expecting*
MoveFile(“test.txt”, “processed\test.txt”)
*Recorded*
0: MoveFile(“test1.txt”, “unprocessed\test1.txt”)
1: MoveFile(“test2.txt”, “unprocessed\test2.txt”)
As you can see, it’s not only much more obvious what’s happening, but you actually get a list of all of the calls that were made on the mock object, including parameters! That’s about half my unit test debugging gone right there. Sweet!
Shouldly isn’t a 1.0 yet, and still has some missing functionality, but I’d already find it hard to work without it. And it’s open source, so get yourself on GitHub, fork a branch, and see if you can make my life even easier!
Programming Magazines – on Paper!
Perhaps strangely for a developer, I much prefer reading from actual, physical books & magazines than a computer screen. This is a bit problematic these days, as what with the rise of the Internet, nobody seems to be printing programming magazines any more (in the UK at least).
As such, I was most pleased to hear about MagCloud, an online service which offers printed magazines in a FUBU (For Us By Us) style. Basically, anyone can upload a magazine in PDF format, and for a charge of around $0.20 a page, MagCloud will print it out and send it to you. This works out at around £5-6 for a magazine of 40 pages, which is a little expensive but not too bad. (There’s a delivery charge of $2-3 too, so you’re better off getting a couple at a time). While the authors can make money from this (by adding on an extra charge per page), none of the ones I was looking at did so.
The two I checked out are well written and informative:
Hacker Monthly, a general programming magazine, and
Rails Magazine, about Ruby/Rails. I couldn’t find any specific .Net ones when I looked, but it’s pretty new so I’m sure one will appear at some point. So if anyone fancies starting a .Net mag, here’s your chance!
Now, many of these are available as PDFs for you to download as well, so you could quite easily print them off yourself and save a few quid. Personally, I’m too lazy/disorganised for that, and I like to have a proper magazine and not a scruffy collection of stapled sheets, but that’s just me.
Check it out. What have you got to lose?!





