Sunday, February 21, 2016

Unquote, App.config, and You

"What curious eye doth quote deformities?"
-- Shakespeare, Romeo and Juliet
Act I, Scene IV, Line 31

I've started using Unquote for my assertions with F# xUnit tests.  I find that its step-by-step failure messages really help in figuring out what is going on.

One thing that really throw me when I first used it was the System.MissingMethodException exception that Unquote was throwing at runtime.  Luckily I was able to find this StackOverflow answer.  It seems that you need to do a binding redirect for FSharp.Core, so you'll need to set up an App.config file in your test project like this example of the Coin Changer kata (using MapFold).



Happy coding.

Monday, February 15, 2016

Behold the Power of Mutation!

"And – ere a man hath power to say ‘ Behold!’ –"
-- Shakespeare, A Midsummer Night's Dream
Act I, Scene I, Line 147

One of the things I found very interesting in the Pluralsight class "Exploring C# 6 with Jon Skeet" was that the new interpolated strings works with expressions.  Since C# is a mutable language we can easily abuse this!



In the above C# REPL we see that we can we can have all kinds of fun as long as we have an expression in our interpolated string.

Example:

var intValue = 0;
var stringValue = $"{((Func)(() => { intValue++; return intValue; }))()}"

As long as the expression has a ToString value it will work.  Note, stringValue will only increment intValue once and after that it will always give the same result, but it is fun nonetheless.

Remember, never under estimate the power to abuse mutable languages!

Saturday, February 6, 2016

Item and Slice F#

"Slice, I say. Pauca, pauca. Slice! That's my humour."
-- Shakespeare, The Merry Wives of Windsor
Act I, Scene I, Line 125

I've been working my way through Dave Fancher's excellent Book of F# and found an interesting example of indexing and slicing arrays in F#.  Since programming is a full contact sport, here is my take on indexing and slicing in F#.



We have a constructor for a type called Word which takes a string and separates it into words.

type Words(sentence : string)

We implement an index with the Item member.

member x.Item(i) = words.[i]

This allows us to access the words of the string given.

Words(sentence).[1]

We also implement an array slice with the GetSlice member.

member x.GetSlice(s : int option, e : int option)

This allows us to slice the array (substring it) of words in the string given.

Words(sentence).[1..2]

We can go one better than built in slice by allow for range in the slice to be bigger than the number of words.

let longer = 100
Words(sentence).[0..longer]

In order to allow for this we have to check to see if the end is greater than the number of words.

if e > words.Length then words.[s..] else words.[s..e]

and

if e > words.Length then words else words.[..e]

I hope I have shown that F# has some very nice support for objects.