Following a visit to Las Vegas a few months ago, I developed an interest in blackjack. According to Wikipedia, the house edge for a casino is typically around 1%. Rather than performing a statistical analysis, I decided to write a blackjack-playing bot and measure its losses.

This seemed like the perfect opportunity to get my feet wet with Haskell. A card game required minimal third party libraries and seemed well-suited to playing with Haskell’s type system.

### The Haskell learning curve

Haskell is not an easy language to get started in. There are excellent online books to get you started (1, 2), and #haskell on Freenode were very helpful. However, the learning curve is difficult at the start.

Every Haskell program requires the programmer to have a moderate understanding of at least the type system and the IO monad. There is a substantial amount of syntax in just this. For example, you will want to learn the do notation (though some consider it harmful) which includes the unfortunately named return function.

For example:

greetingForUser is a value that, when evaluated, takes a line of input from stdin and returns a string containing that name wrapped in a friendly message.

So, what’s going here? getLine has type IO String, a string which is marked as having come from the outside, impure world. You can evaluate it twice and get different outputs. do notation allows us to use the string as a simple String, enabling us to keep IO actions out of the third line. return then wraps greeting in IO again.

Got that? Understanding IO is a conceptual hurdle you must overcome before you can start writing useful code.

### Getting the code

My blackjack code is available on GitHub. The player’s tactics are not optimal, but losses are around 2%.