First Haskell project: Mastermind solver

2017-05-19

In some of my spare time, I have started learning some Haskell, mainly using the free online version of the book Learn You a Haskell for Great Good. It has been fun to wrap my brain around concepts from functional programming; it definitely makes for a different way of solving problems.

As a first mini-project, I wrote a simple solver for the game Mastermind. The code is up on GitHub. This project lends itself well to taking advantage of Haskell's list comprehensions and filtering. Basically, there's a large but finite space of possible patterns, and each guess is scored based on its closeness to the correct one. You can win by keeping track of the space of remaining possibilities based on each guess and its score, and simply making guesses that remain possible. In Haskell, you can easily define a list of possible guesses, narrow down its contents with a filter, and then call head on the remaining list to get your next guess. Presumably, thanks to Haskell's lazy evaluation, the compiled code need not ever load the full list into memory to accomplish this.

I may add some more functionality to the code as far as allowing the user to specify different game parameters or try different guesses. There are also some more efficient algorithms that I could try implementing. (One of these was apparently written by Donald Knuth!) For now, I am pleased enough to get something working beyond the "hello world" basics. The project taught me more about Haskell's IO than I would have figured out from something simpler. I also had to stretch my brain to get the comparison function right using purely functional code. I found that when I think about how to implement certain types of counting, I naturally think in a more imperative way. The functional focus of Haskell has definitely provided me with some good brain stretching.