Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, March 12, 2016

How I Learned to Love Loosely Coupled Test Data

"Play fast and loose with faith? So jest with heaven,
Make such unconstant children of ourselves"
-- Shakespeare, King John
Act III, Scene I, Lines 242-243

For C# development, I love to use AutoFac!  I find that AutoFac allows me to change the design of my code without having to worry about decencies.  The last thing I want to have to do while refactoring my design is fix a bunch of broken unit tests.  Typically if find that I have to support hard coded test setup for the system under test, when I change the signature of the constructor I'll also need to change all the test setups related to the class (this is often the case in code in which I was not the original author).  This can become very annoying, since the test cases often do not really care about the setup of the system under test.

If you are using a decency injection framework like AutoFac you really need to pair the loose coupling of your production code decencies with loose coupling of the setup of your system under test.  Loose coupling of the setup of your system under test is exactly what a test fixture is for.

Personally I love AutoFixture for C# development!  AutoFixture does all the hard work of creating a test fixture for you, all you have to do is walk up to it and ask it for what you want.

If you are using AutoFac or some other IoC framework in your system under test, more likely than not, you are using a mocking framework like Moq or Rhino Mocks.  Well, AutoFixture has you covered by allowing you to use an auto mocking plugin for Moq, Rhino Mocks, or whatever.  By using auto mocking along with AutoFixture you are able to create a system under test with all the decencies already mocked out.

With AutoFixture creating the system under test for you, you can freely change the signature of your constructor for your system under test without the need to change any of the setup for the test cases!

Say we have the following:



The above is a fairly common example of C# application that I work with.

We see that we are testing using two different test classes, one using AutoFixture and one not.  If we uncomment out the ILog decency in the System class we would break the test setup in the test class ProgramTestsWithoutAutoFixture, but the test class SystemTestsWithAutoFixture would continue to work!  For such a simple example this might not matter, but with larger code bases this can become an issue.

By using AutoFixture with Moq we are pairing the same loosely coupling of the creation of our system under test with the loosely coupling we get for our decencies in our production code using AutoFac.  Truly one can say, AutoFac iff AutoFixture with Moq.

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!

Sunday, January 10, 2016

Data Structures Matters

"I see thee yet, in form as palpable"
-- Shakespeare, Macbeth
Act II, Scene I, Line 31 

One of the katas we like to use at work while interviewing candidates is the Roman Numeral kata.  It is a simple kata in which you create a function which takes an integer and gives you back a string representing the roman numeral representation of the number.  It is fairly simple to explain but is deep enough to get a good idea of how the person works.

Here is a possible solution to the Roman Numeral kata in C#.



Looking at this solution we see a few things.  The solution is using C# 6.0 syntax but beyond that we see three major things.

  1. translation are being applied using the higher order function Fold (in C# Aggregate)
  2. mutation of the input value is used to maintain state through iterations
  3. translations are held in a Dictionary
Let us look at the Dictionary data structure which is the main focus of this post.  In general a Dictionary is not ordered, now some implementations are ordered in the order in which the key value pairs are inserted (this is the case with the C# implementation), but this is not a property of the Dictionary data structure (see also the NIST entry).

Here is a possible solution to the Roman Numeral kata in Clojure.


Looking at this solution we see a few things.
  1. translations are being applied using the higher order function Fold (in Clojure reduce
  2. hash maps are used to maintain state through iterations
  3. translations are held in a vector of vectors
We see that we cannot use a Dictionary (called maps in Clojure) to hold the translation.  Clojure's HashMap uses Phil Bagwell's Hash Array Mapped Trie which makes no claim about order, in fact we see that maps (and sets) are unordered while vectors (lists and seq) are ordered.  Since our algorithm requires that the translations be in the order we insert them we must use a data structure which preserves this order.  Thus we must used something that is ordered like a vector.

How about F#?  Here is a possible solution to the Roman Numeral kata in F#.


Looking at this solution we see a few things.
  1. translations are being applied using the higher order function Fold (using F#'s List.fold)
  2. tuples are used to maintain state through iterations
  3. translations are held in a List
For the same reasons that we found in the Clojure solution we cannot use a Dictionary (called a Map in F#) since they are ordered by F#'s generic comparison and not in the ordered in which they were inserted.  Luckily we can use a List which is ordered.

There you have it, the Roman Numeral kata in three different languages.  Despite being a simple kata we have learned something about the Dictionary data structure, mainly that it does not have an order and thus should not be used in cases in which order matters.

Sunday, December 13, 2015

Round and Round We Go OR How to Stop Circular References in AutoFixture

"That many things, having full reference"
-- Shakespeare, Henry V
Act I, Scene II, Line 205

I love to use AutoFixture to setup the the arrange part of my tests.  I find that working without worrying about the arrange allows me to focus more on the task at hand.  A possible downside of working this way is that AutoFixture is mindlessly setting up all the test data.

Having AutoFixture setup your test data is fine when working with green field classes but when working with legacy code and third party code you getting into cases in which you have circular references.  What do I mean?  Compare the following:

Case 1:

class A has members with type B
type B has member with type C
type C is a primitive

Case 2:

class X has members with type Y
type Y has member with type Z
type Z has member with type X

In case 1 we have a termination point with type C, AutoFixture can happily go about and create an instance of A and populate all the members in the hierarchy with data.

In case 2 we do not have a termination point, Z has a member of type X which a member of type Y which a member of type Z which goes back to X and so on.  Case 2 has a circular reference and AutoFixture is unable to give us back an instance of X without going into an endless loop.  Luckily AutoFixture is smart enough to figure out that it is in an endless loop and will error out telling us about the issue.

What do we do if we have a class like X in legacy code or third party code?  We'll we can tell AutoFixture that we will have classes like X but that it is fine to just terminate the repeating hierarchy with a null or empty.  We use the following to do that:



I normally put this in my TestInitialize for the test class of the offender, but I can see putting in the arrange of a test class if you are mixing old and new.  There you have it, a way to use AutoFixture with dirty old classes.


Sunday, December 6, 2015

AutoFixture for the Win

"What have I kept back?"
-- Shakespeare, Antony and Cleopatra
Act V, Scene II, Line 147.2

Anyone who has paired with me while working in C# knows that I am addicted to AutoFixture.  Now I do not try to add it to everything that I am working, but usually it finds its way into whatever I am working on.  Why?  Simply put, using AutoFixture allows me to focus on the task at hand.

Here is a quick example:



In this example I am implementing the higher order function Map using the higher order function Fold (see my other post if this interested you).

What do you not see in the tests?  The setting up of the test data.

Why?  It is not important to the task at hand.  We do not need it to test the behavior of Map.  Map takes a collection and a function and applies the function against every member of the collection producing a new collection.  What we want to verify is the applies part, which only requires a collection and a function, the actual members of the collection (and the function) do not matter for this verification.

Staying focus on the task at hand is the power of a test fixture and having someone else implement the test fixture for you is even better.  Using AutoFixture with xUnit you really do not need to think about setting up test data at all and that is good thing.

Sunday, October 11, 2015

Folding Up the Coin Changer Kata

"Whate'er the course, the end is the renown."
-- Shakespeare, All's Well That Ends Well
Act IV Scene IV, Line 36

Coin Changer Kata


The Coin Changer kata has three things which make it a good kata.

  1. easy to understand
  2. rich set of features
  3. lots of realistic possible implementations
Even in today's cashless society, most people understand the idea of handing someone over some money and get change back.  This handing back of change requires the breaking down of the change over coins of different denominations.  Finding which coins to hand back has lots of possible implementations which translate over to things which programmers do every day.

The user story is very simple:

Given a collection of coins of different denominational value
When an amount of change is given
Then it will give back the number of coins for each denomination needed using the least amount of coins possible

A type signature for the function needed could look like the following:

changeFor(coins: int[], amount: int): int[]

We are expecting an array of integers which have different denomination of coins (in the US something like: [25, 10, 5, 1]) and the amount of change needed (something like: 99) giving a resulting array of integers showing how many of each denomination (something like: [3, 2, 0, 4]).

What would we need to be able to do this kata using just Fold?

We'll need to use a tuple (or something like one) to manage the state of the amount of change needed and the resulting array of integers.


Now lets look at an example using a typical full US register with quarters, dimes, nickels, and pennies.  We'll look at getting change for 99 cents.


First Memorize has (99, empty) and X has 25 giving the result of (24, [3]).


Next Memorize has (24, [3]) and X has 10 giving the result of (4, [3, 2]).


Then Memorize has (4, [3, 2]) and X has 5 giving the result of (4, [3, 2, 0]).


Last Memorize has (4, [3, 2, 0]) and X has 1 giving the result of (0, [3, 2, 0, 4]).


Finally obtaining the tuple item with the resulting array of integers to get the change.

Clojure




We see with the Clojure code that we seed with a map with a key for the :amount and one for the :result.  We fold over the coins using reduce destructing the memoize value into the amount and result.  We then just calculate the new amount using: amount % coin, follow by inserting the number of coins we get using: amount / coin.  We use cons to show off the coolness that is the thread-last macro (at least that is why I think I coded it this way, it was a little bit ago that I did the gist and I cannot remember why I code with cons over conj).

C#



We see with the C# code that we seed using a Tuple (which I think has very ugly syntax in C#).  We then fold over the coins using aggregate just like the Clojure code above.  We calculate the changer results and place them into a new Tuple which we return as the memoize.

ECMAScript 2015



In this ECAMScript 2015 example we use lodash's foldl to fold over the coins just like the two examples above.  The seed value is a simple JavaScript object with the members of amount and result given.  We are a bit dirty and mutate the memoize on each call with the changer results but we could argue that this is still "pure" since the mutation happens to an item which is created and used only in side the function.

ECMAScript 2015 and Immutable.js



Last we look at Facebook's open source Immutable.js.  We create an immutable List with the coins which we use to fold over the values using reduce.  The seed value we give it is a simple JavaScript array with an immutable List to hold the results and the amount passed in.  We could use an immutable Map if we wanted to keep it purely immutable.  Like this:



I am not a huge fan of stringly typed accessors, but I understand why they use them.  Both ways are good and would really come down to to performance and readability.

The End


Thus ends our tour of All You Need is Fold, but this is not the end of the uses of Fold, for Fold is universal.

Sunday, October 4, 2015

Fold the Zip Up

"They fell together all, as by consent."
-- Shakespeare, The Tempest
Act II, Scene I, Line 207

Zip


Zip can be thought of as the more generic form of Map.  Think of Zip as applying a function against each member of the collections given to it, thus mapping more than one collection to another collection.  It is a lot easier to see than to explain in words.

I believe Zip2 would get the following definition:

zip2 :: (α → β → γ) → ([α] → [β] → [γ])
zip2 f = fold (λx y xs ys → f x y : xs ys) [ ]

This would be if we limit Zip to being used on 2 collections (this is mine definition, Dr. Graham Hutton has nothing to do with this definition, blame me if it is wrong).

Folding a Zip we'll need a collection to seed with then we just apply the given function against each member from each collection concatenating it with the seed, just as we did with Map.



Next we'll look at a simple example adding the members of two collections together.


First Memoize has nothing and X has 1 while Y has 10 giving the result of 11.


Next Memoize has 11 and X has 2 while Y has 20 giving the result of 11, 22.


Lets see some code examples.

Clojure




With Clojure we do not have to worry about the number of collection we'll give our Zip function since we can use destructing to say and everything else.  We can then apply map to create a vector containing all the elements next to each other, we'll see this is common in the other languages since the implementation of reduce is only design to work with a single collection.  From here it is just like Map except that we need to use apply since are members are a collection themselves.

C#




With C# we have to specify the number of collection we are going to Zip, in this case we'll do two.  We need to Zip the members from the two collections together into a Tuple (which is a bit of cheating but I can find no other way to do it with LINQ).  From there it is just like Map.  With this implementation we do have a limitation in that the two collections must be the same size, since to get around that would be a bit of work and we rather have a readable implementation than perfect code.

ECMAScript 2015




In ECMAScript 2015 (also known as JavaScript ES6), we see an implementation similar to the C# code except we use lodash's zip to place the members in a single collection (lodash's zipWith is like LINQ's Zip).  From there it is just like Map.  With this implementation like the C# implementation we have a limitation in that the two collections must be the same size, and again the work around would be a lot of work so we'll error on keeping the code readable.

Done


There you have it showing once again that all you need is Zip.

Sunday, September 20, 2015

The Cloud-Capped Towers OR AutoFixture

"The cloud-capped towers, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,

Leave not a rack behind. We are such stuff
"
-- Shakespeare, The Tempest
Act IV, Scene I, Lines 152 -156

In my day-to-day work I do a lot of .Net programming.  It seem at some point in each of the applications I am either enhancing or creating I ended including Mark Seemann's AutoFixture (if it is not already in use).  AutoFixture is an easy way to create a fixture object.  A fixture object is an object which centralizes your helper methods in your test code, like methods which create your system under test and help generate test data.

Fixture objects are great and I often find myself wanting one in my day-to-day work, but I am lazy.  Since I am lazy I do not want to go to all the trouble of creating my own fixture object, to quote Homer Simpson, "Can't someone else do it".  Luckily in the .Net realm someone already has, Mark Seemann.  AutoFixture lets you get the best of all worlds, you get a fixture object and you do not have to write the framework around it!  (working with it for a few years now, I can say it is well thought out and not a big hair ball, see also Simple Made Easy for the full reference)

How about some examples?  (taken from the AutoFixture cheat sheet and rewritten using xUnit)



We see in the above lots of wonderful things.
  • We can walk up to the fixture object and ask it for some test data.  
  • We can use the AutoData attribute and ask for test data.  
  • We can register implementation for abstract types.  
  • We can create collections of test data.
  • We can build specific test data saying what attributes we care about and letting the fixture object set up the rest.
  • We can even have a do method to allow for modification outside of the object we are having the fixture object create (this is not good design but sometimes it is needed).
As I work more with AutoFixture I find more and more uses for it.

Another framework I use a lot in my day-to-day .Net programming is Moq.  Guess what, AutoFixture can be uses as an auto-mocking container with Moq (and it has plugins for other mocking frameworks too).

Yet another example.  (using MS Test taken from an overview of AutoFixture I did at work recently)



We see in this example that we had a simple class called Echo which got top hatted into having logging and a backup added to it.  The interactions with the logger and back-upper need to be tested, luckily we can tell the fixture object that we would like to get spy objects for the logger and back-upper.  These spies from AutoFixture are Moq mocks which allows us to verify that the behaviors we want.

By using AutoFixture and Moq we can meet all the "needs" of Top Hats everywhere.

(The term Top Hats comes from Uncle Bob's Clean Coder series episode 7, in which there is a scene with an Architect talking about choosing an IDE and Database for a project hence the term Top Hat and top hatting to describe this type of "architecture".)

I find that AutoFixture allows me to simplify my test code (simple as discussed in Simple Made Easy) and allows me to stay focus on what I am actually trying to test.

Sunday, September 13, 2015

Filter, Guarding You From Fold

"You and your ways; whose wraths to guard you from,"
-- Shakespeare, The Tempest

Filter


Filter is a lot like a higher order functional bouncer, it prevents undesirable elements from getting into the resulting collection.  


A simple example would be a filtering with a function which says if a value is odd or not.




In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", he gives the following definition of Filter in terms of Fold:

filter :: (α → Bool) → ([α] → [α])
filter p = fold (λx xs → if p x then x : xs else xs) [ ]

From the definition above, we see that Filter is just Map but with a predicate clause stating if the element should be placed in the resulting collection or not.


Let us look at an example using my name Mike and a function which will check if a character is lower case.

(similar to Map last time)


First Memoize has nothing and X has M.


Next Memoize still has nothing (since M is upper case) and X has i.


Now Memoize has i and X has k.


Then Memoize has i and k while X has e.


Now the Filter will return the result of "ike".

Now what we all came to see, some code examples.

Clojure



In Clojure we can use the reduce function to move through the collection checking the predicate condition with the if macro guard against undesirable elements.

C#



With the C# code we'll need to create some type of collection with the seed value which will allow us to add elements to it, we'll use the collection class of List.  We'll simply iterate through the collection using Aggregate and add elements to the memoize List if they pass the predicate clause.

ECMAScript 2015



In the code above that we'll use the build in JavaScript array method of push to add an element which gets past the guarding predicate function to the array at the end.  We are simply move through the collection we are filtering, pushing elements into the memoize array.

Fin


There you have it we are able to keep the riffraff elements out using Fold. 

Monday, September 7, 2015

Folding into Map

"I have forgot the map."
-- Shakespeare, Henry IV Part I
Act III, Scene I, Line 5

Map


Map is the first of the big three Higher Order Function we will looking at Folding using Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", as a guide.  The idea of a Map is simple, you have a collection which you wish to apply some translation function against every member of the collection.

We can look at a few simple examples, the first of which would be the identity function.


 Next we can look at a constant function which maps turtle for any value given to it.


Last we can look at a function which shifts everything given to it.


All of this these functions have something in common, they all apply a function against every single member of the collection they are given, thus the resulting collection is the exact same size as the collection given to it.

We can now look at how we would implement Map using a Fold.  We see that Dr. Hutton gives Map the following definition:

map :: (α → β) → ([α] → [β])
map f = fold (λx xs → f x : xs) [ ]

Folding a Map we'll need a collection to seed with then we just apply the given function against each member concatenating it with the seed.


(similar to Reverse from last time)

Let us look at an example of upper casing Mike.


First Memoize has nothing and X has M.


Second Memoize has M and X has i.


Third time Memoize has MI and X has k.


Finally Memoize has MIK and X has e.


Giving the final result of MIKE.  Now let us look at some code examples.

Clojure




In Clojure we use the reduce function to Fold.  We give the reduce a seed of an empty collection and use conj to join applying the function given with the resulting collection.

C#




With C# we use the aggregate LINQ function to Fold.  We give the aggregate a List and add the result of applying each member of the given collection against the function we are mapping with.

ECMAScript 2015




Using ECMAScript 2015 (aka JavaScript), we use lodash's foldl to Fold.  We give the foldl an empty array and push the result of applying the function given against the member we are mapping against.

To End All


There you have it by folding with an empty collection and applying the given function against each member adding the result against the seed and you have a Map.


Saturday, August 29, 2015

Displanting a Function OR Folding a Reverse

"Displant a town, reverse a prince's doom"
-- Shakespeare, Romeo and Juliet
Act III, Scene III, Line 60

Reverse


The interesting thing about the Reverse function is that it is not really doing anything.  With a small clerical error in a visit and recombine function you have reverse.

In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the following definition is given for reversing:

reverse :: [α] → [α]
reverse = fold (λx xs → xs ++ [x]) [ ]

We see that we concat the memoize with the member, in that order, thus reversing the collection.


Since I like advertising myself, let us go through an example with my name (someone has to advertise for me).


First time the Memoize has nothing and X has M.


Second time the Memoize has M and X is i.


Third time Memoize has i and M and X has k.


Fourth time Memoize has k, i, and M while X has e.


Leaving us with ekiM.

Let us look at some code examples.

Clojure




We see with the Clojure code we are using the cons function to place the current member in the front of the memoize.  We do this for the whole collection thus giving us the collection in reverse.

C#




With the C# code we see that we need to create something to contain the resulting collection, in this case we'll create a List.  We create the reversed collection in an immutable way by creating a new List every time in the lambda.

ECMAScript 2015




With JavaScript (ECMAScript 2015) we us the unshift method on the array.  Since unshift returns the length of the array after the member is added to the head of the array (which I totally did not expect) we need to manually return the memoize after applying unshift.

Fin


There you have it again, yet another function which can be created using Fold.  Showing once again that all you need is Fold.

Sunday, August 23, 2015

Think About Length OR How Fold Can Do Everything, Even Count

"Leave nothing out for length, and make us think"
-- Shakespeare, Coriolanus
Act II, Scene II, Line 47

How Long is It?

I am not sure why but before I start reading a chapter or watching something I've recorded I almost always check to see how long it is.  Today's post will be using Fold to find the length of a collection.  In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the following definition is given for finding the length:

length :: [α] → Int
length = fold (λx n → 1 + n) 0

We see with this definition we do nothing with the current member of the collection (x above) and instead only act on the memoize (n above).


In the simple example below we will see that the string "Mike" has 4 characters in it.

At the start we have a Seed of 0 and a collection with the members M, i, k, and e.


First time Memoize has 0 in it and X has M.


Second time Memoize has 1 in it and X has i.
Third time Memoize has 2 in it and X has the letter k.
Last time Memoize has 3 and X has e.
There you have it (maybe I should have used my sister Kim name instead).  Let us see some code.

Clojure


We see in the clojure example that function we give the reduce must have two parameters, so we call the second one _ to denote that it is not used.

C#


With the C# code the lambda we give Aggregate has two values of which we give the second one the name of _ to denote not using it.

JavaScript (ECMAScript 2015)


With ECMAScript 2015 we use lodash's foldl and see that the lambda only has to have one value which is the memoize.

Fin

There you have it counting with Fold, showing that you need is Fold.

Sunday, August 16, 2015

If True or False I Know Not

"I idly heard; if true or false I know not."
-- Shakespeare, King John
Act IV, Scene II, Line 124

Welcome Back


This is the next in the series of post on Dr. Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", this time around we'll look at Oring.  Dr. Hutton has given Oring the following definition:

or :: [Bool] → Bool
or = fold (∨) False

The idea is that we Fold an Or function with a seed value of False.  If one of the members of the collection is True we Or it with False giving us True, else if none of the members of the collection are True we will end up with the value of False.


In the simple example below we'll see that if we have a single value of True then the end result will be True.

At the start we have a Seed value of False with collection containing False, True, and False.


First time the Memorize has False and X has False.


Second time the Memorize has False and X has True.


Third time the Memorize has True and X has False giving use the finally value of True.



Let us now look at this in sweet, sweet code.

Clojure



In the Clojure code that we use the or macro and a seed value of false in order to create an Oring function using the higher order function of reduce.  Since reduce is expecting a function and not a macro we need to create a lambda function to wrap the or macro.

C#



We see in the C# code that we can use the LINQ aggregate method on the collection we are folding.  We give the aggregate a seed value of false and in the lambda we simply takes the memorize and the current member and or them.

JavaScript (ECMAScript 2015)



Using lodash's foldl function along with Babel.js we are able to create an Oring function by folding over the collection and passing it to a lambda function which ors the current member of the collection with the memorize value.  We give a seed value of false thus causing the initial value of the memorize to be false.

Until Next Time


There you have it an Oring function using nothing but Fold.  Thus "proving" that all you need is Fold.


Sunday, August 9, 2015

Approaching the Fold

"Approach the fold and cull th' infected forth"
-- Shakespeare, Timon of Athens
Act V, Scene IV, Line 43

Welcome


In Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the first function that is looked at is And.  Dr. Hutton gives And the following definition:

and :: [Bool] → Bool
and = fold (∧) True

The idea being that we give Fold an And function with a seed value of True.  If one of the members of the collection given is False the Anding it with True will yield a value of False and thus the end result will be False.  If no member of the collection given is False then the end result will be True.


Let us look at this in code.

Clojure




To create an Anding function we'll use reduce along with the and macro with a seed of true.  Since and is a macro, we'll need to wrap it in a function in order to be able to use it in reduce.

C#




We'll use the LINQ function Aggregate along && and a value of true to create an Anding function.

JavaScript




We see that by using lodash's foldl function with && and the value true we can create an Anding function.

ECMAScript 2015




Since we live in the future, we'll use Babel to allow us to use ECMAScript 2015.  We see again that by using lodash's foldl with && along with the value true we now have an Anding function.

Fin


There you have it the And function using Fold, showing once again that all you need is Fold.

Saturday, April 4, 2015

Zipping in SQL

"That I am that same wall; the truth is so."
-- Shakespeare, A Midsummer Night's Dream
Act V, Scene I, Line 160

SQL and higher order functions are completely different.  SQL is used to apply functions against collections of data, while higher order functions are used to apply functions against collections of data.  Totally different.

I mean have you ever seen both Michael Fogus and Itzik Ben-Gan talked about in the same blog post?!?

I have no idea why people classify declarative programming with SQL as completely different than declarative programming with higher order functions.

I'll use this blog post as a jumping off point to show that they are very similar things.

Let's look at the higher order function of zip.  The idea of zip is that you take two or more collections of data and zip them together forming one collection of zipped data.  Say you have a collection of greetings ["Hello", "Hi", "Aloha"] and another collection of names ["Mike", "Kelsey", "Jack"].  Given a zip function which takes one string and concats it with ", " and another string you could zip these collections together with that zip function obtaining the following collection ["Hello, Mike", "Hi, Kelsey", "Aloha, Jack"].

Let's look at this in some code.



In the first example we have C# using the zip method on the String class.  For the C# zip, we need two collections and a lambda express.

In the second example we have Clojure using the map function.  For the Clojure map, we need a function and one or more collections (in this example we have two).

In the third example we have T-SQL using an INNER JOIN along with a CONCAT in the SELECT statement.  An INNER JOIN you say?  Yes, an INNER JOIN can be thought of as the same thing as a zip.  The key is that the key you are matching on (in this case the ROW_NUMBER) needs to match.  In the Clojure example we are using a vector which is an associative data structure with the keys being the index values, which is the exact same thing we have in the SQL!

Please play around with the fiddle I created to show this in action.

Sunday, March 15, 2015

Examples of Map as a Series of Applying a Function -- in Clojure and kind of in C#.

"It is now apparent?"
-- Shakespeare, Measure for Measure
Act IV, Scene II, Line 135

Every now and then you read something and think, that is exactly what I have been thinking to myself but could not find the words.  Such an experience happen to myself this week.

I was reading Clojure Programming by Chas Emerick, Brian Carper, and Christophe Grand and found exactly how I have been thinking about the higher order function map but have not been able to express in words properly (it is on page 62 in the first edition).

map f [a b c] can be expressed as [(f a) (f b) (f c)]

Likewise map f [a b c] [x y z] can be expressed as [(f a x) (f b y) (f c z)] and so on ...

So what would this look like in code?

Glad you asked.



We see that in Clojure we can get exactly what we are looking for.  As a comparison we fins that in C# using the Zip we can get fairly close.

Sunday, March 1, 2015

Roman Numeral Kata in One Line with C#

"When in one line two crafts directly meet."
-- Shakespeare, Hamlet
Act III, Scene IV, Line 211

The idea of the Roman Numeral kata is that given a number between 1 and we'll say 4999, the number will be converted into the Roman numeral form.

f(1) = "I"
f(2) = "II"
f(3) = "III"
f(4) = "IV"
f(5) = "V"
...
f(4999) = "MMMMCMXCIX"

You can test a value using Google's search by typing the number and "to roman".  Try searching for "299 to roman" to test it out.

At work, we have been using the Roman Numeral kata for interviewing candidates.  The idea is that we get an idea of what it is like to work with the person and they get an idea of what it is like to work with us.  As an added bonus there is a good chance that we will learn something new from each other in the process.

On one such interview recently, we had a candidate do something rather interesting.  Typically a candidate will just start with a series of if statements, some candidates will replace the ifs with an associative data structure (called dictionary in C#), but most will not.  This candidate did a transformation of the input into a string of "I"s and then replace those with the Roman numeral.  They did not ended up finishing or even coming to a general pattern, but I found this idea interesting and ran with it coming up with a C# one liner.



We see in the code above a few different things.

To make this a REPL one liner we create a Func which takes an integer and returns a string, we then start the lambda expression with the bond variable of number.  (In the refactoring done on the candidates code this was all in a single return statement in a method not a Func variable, but when I redid it for this post I did it on the Mono REPL as a Func variable.)

Func<int, string> toRoman = (number) =>

After that we have our associative array, which allows us to look up each of the transformation that we will be doing, this is very useful since to add another transformation we just need to add an entry to the associative array.  (I've done this kind of thing in real world application but I normally will make the look up be a private member of the class.)

new Dictionary<int, string>
{
{1000, "M"},
{ 900, "CM"},
{ 500, "D"},
{ 400, "CD"},
{ 100, "C"},
{ 90, "XC"},
{ 50, "L"},
{ 40, "XL"},
{ 10, "X"},
{ 9, "IX"},
{ 5, "V"},
{ 4, "IV"},
{ 1, "I"}
}
**Note, you do not need the "I" entry in the associative array do the the seed value of the fold, but we'll leave it in there since it is from the more general way of doing this kata.**

We then take this and run it through a fold (called Aggregate in C#).

.Aggregate(

In the seed value to the Aggregate we create a transformation string of the "I"s equal to the value given by the caller.

t(1) = "I"
t(2) = "II"
t(3) = "III"
t(4) = "IIII"
...
t(20) = "IIIIIIIIIIIIIIIIIIII"

To do this we use the string constructor that takes a character and the number of times you wish that character to repeat.

new string('I', number),

We then have the lambda of the Aggregate in which we simply take the current Key and Value from the associative array and call Replace on the transformed string replacing the number of "I"s given in the Value with the Roman numeral given in the Key.

(m, _) => m.Replace(new string('I', _.Key), _.Value));

This is not the "best" implementation of the Roman Numeral kata, but it is a one liner!



"The one I'll slay; the other slayeth me."
-- Shakespeare, A Midsummer Night's Dream