Fork me on Github

Fork me on GitHub

Sep 19, 2012

The Zebra Puzzle implemented in FSharp

Yesterday I had the opportunity to show a solution at the Zurich FSharp Users Meetup Group.

I chose to show a small example of the Zebra Puzzle and an implementation of the solution to it in F#.

The implementation is rather basic as it uses simple integers to assign the attributes to the house. A more type safe implementation using a discriminated union for each attribute type is a good idea, more to follow on that in a later blog post with an improved example. Please find the code below.

Credits to Tomas Petricek, whose implementation of the permutations of a list I used from Stack Overflow.

The solution is shown below or under this link.

Jul 3, 2012

Calculating outcomes of Texas Holdem poker, functional approach with CSharp

Taking part in the Udacity CS212 course inspired me to take a look at how to calculate outcomes for Texas Holdem poker.

I created an C# application to calculate poker outcomes and uploaded it onto my GitHub account.


Looking at other programming languages has been really instructive in that it has changed the way that I look at my C# code.

For example I used the following two list comprehensions with LINQ.

        // returns all pairs, disregarding order, 
        // that can be chosen from the remaining cards in the deck
        public static IEnumerable<List<PokerEntities.Card>> GeneratePairs(
              this List<PokerEntities.Card> remainingCards)
        {
            var allPairs =
                from cardOne in remainingCards
                from cardTwo in remainingCards
                where !cardOne.Equals(cardTwo)
                where cardOne.CompareTo(cardTwo) == 1
                select new List<PokerEntities.Card> {cardOne, cardTwo};

            return allPairs;
        }

        // returns all triples, disregarding order, 
        // that can be chosen from the seven cards in the flop
               public static IEnumerable<List<PokerEntities.Card>>
                    GenerateTriples(this List<PokerEntities.Card> theFlop)
        {
            var allFlopTriples = from cardOne in theFlop
                                 from cardTwo in theFlop
                                 from cardThree in theFlop
                                 where !cardOne.Equals(cardTwo)
                                 where !cardTwo.Equals(cardThree)
                                 where !cardThree.Equals(cardOne)
                                 where cardOne.CompareTo(cardTwo) == 1
                                 where cardTwo.CompareTo(cardThree) == 1
                                 select new List<PokerEntities.Card> { cardOne, cardTwo, cardThree };
            return allFlopTriples;
        }
I have implemented all the functionality as pure functions, which renders a bit of performance penalty in C#. More blog entries will follow on how I optimize the code to get rid of these performance bottlenecks.

Jun 23, 2012

Starting with Clojure

This post shares some tips and tricks for getting going with Clojure on a mac. First step is to install clojure from here. To get a nice a not too fast-paced introduction to the language I read the Clojure chapter in the great book Seven Languages in Seven Weeks.

Then you will want to install Leiningen, which is a building tool for Clojure that also provides a REPL.

There was a small trick required first, and that is to add the place where you put the Leiningen file to the $PATH.
I put the lein file into ~/bin and added this folder to the path by creating a .bash_profile file in my home directory with the command
vim .bash_profile

in the file I added
export PATH="$HOME/bin:$PATH"

restarted the terminal window, and saw that it worked by
echo $PATH

you launch it by using the command
lein repl


A small thing that I had to look up is how to add some set functions (not part of the core Clojure libraries)
The command is:
(require '[clojure.set])


Another gotcha is the difference between symbols and keywords.
Keywords are like erlang atoms and symbols are referring to something else than itself, like say a let-binding. All keywords are prefixed with a colon in Clojure, like so 
:car


A handy way to find out more about functions, is the doc feature, like so:
(doc str)


Anonymous functions in Clojure are defined with the command:
(fn [parameters] (function))


An abbreviation for the fn command is the hash symbol #, and this is what is used for declaring lambda expressions.








May 30, 2012

Heathrow route planning with Erlang, FSharp and CSharp

I have started a journey to learn more languages and comparing their benefits and drawbacks

An interesting problem that I recently came across is this one from learnyousomeerlang.com. The problem is to calculate the shortest distance to the end nodes in the grid. Here how I solved it using Erlang:



After having solved with Erlang, my second attempt was FSharp. I expected that these two could be very similar due to their shared functional paradigm, and indeed that came out fairly clearly.



I also decided to solve the problem with CSharp, which has a less explicit functional orientation. I kept the main approach from the Erlang and FSharp implementations, which may have contributed to the CSharp solution not being very idiomatically coded. Any suggestions on how you would have gone about the problem solving in CSharp differently are most welcome (please comment on the post)




Apr 20, 2012

Starting with Haskell

First disclaimer/setting of context. I am a beginner when it comes to Haskell, so this post will not contain any deep insights into the Haskell language, rather some links, tips and tricks and code snippets that I have been playing with during my first hours discovering the language.
(the purpose of this write-up is a note to self and hopefully it can also help other beginners to get started with the basics)



A really useful resource that I have spent some time with, both reading full sections and using as a reference, is learnyouahaskell.com. It is a book published in its entirety on the web and that also can be bought if you find a soft copy easier. Another good a freely available book is Real World Haskell.

Getting Haskell going on a PC has proved to be easy, I just went to haskell.org and downloaded the Windows version. From the Win Haskell package I use WinGhci, which seems very stable and is straight forward to work with. If you come from an FSharp background, you can think of this tool as the FSharp interactive window that you are used to from Visual Studio.

A gotcha is that you need to use the ghci specific let keyword to make definitions in the interactive window.

Some commands, more focusing on the handling of the IDE than actually showing any Haskell (the book examples are the best resource for that).

To toggle type display in ghci:


to load a haskell file (file extension .hs)

To find out details about a name, you can use the :info ghci command, more details here.

A really useful resource to find out more about Haskell commands, is hackage. This can be used as a programming reference. I have used it to find out more about the Base package, which is the standard package that is loaded whenever you start Haskell.

A syntax that has stood out to me as really powerful so far in Haskell is List comprehensions. You can surely  find better and more detailed explanations of it here and here, but in short you specify an output function and generators/predicates. The syntax looks like this:


List comprehensions can be very useful for solving combinatorial problems.

Another really useful resource is Hoogle. It is a search engine for haskell functions and great help as a syntax reference.




Mar 11, 2012

Google Apps Script - Find from right

I am getting familiar with Google Spreadsheets and Google Apps Script.

For a sheet used for expense tracking I needed a findFromRight function in Google Apps Script.

I let myself be inspired from the Excel VBA world and found something from Chris Rae's site that could be modified:



To add testing to this Google Apps Script, I decided to try out the GAS-Unit testing framework.




There are two ways to view the test results. The code above only prints to the log view (View-> Logs in the menus). It is also possible to receive the test result as a formatted report per mail (by including the outcommented line and updating the email address).

All in all, I find that using the testing framework can be of good help to establish that the functions are working as expected (and keep working as expected when redesigned).

Mar 4, 2012

Select arrays in Microsoft Excel 2010

I am getting comfortable with changing from Excel 2003 to Excel 2010.

One difference that I have noticed in the two versions, is how the array formula entry behaves on already existing arrays (pressing ctrl-shift return).

In Excel 2003, after array formula entry, the current array gets selected.
In Excel 2010, after array formula entry, the current cell gets selected.

Please see illustrated example below:

Excel 2003

A basic array formula is entered


After array formula entry (ctrl-shift return), the current array is selected


Excel 2010
A basic array formula is entered

After array formula entry (ctrl-shift return), the current cell is selected

If we want to select the current array in Excel 2010, another method is necessary
Select goto special in the ribbon menu

and choose current array in the panel that shows