Brandon.Si(mmons)

code / art / projects

Partial Application and a Simple Mastermind Game

I thought this was a good, simple example of how currying and partial application can be used in a very expressive way. We create a one-liner to play the game mastermind.

In the type signature we include unnecessary parentheses, to be clear that we are thinking of the function not as “a function taking a secret code and a guess and returning a score for the guess” but as “a function taking a secret code and returning a scoring function for that code”.

1
2
3
4
5
6
7
8
module MasterMind
    where

-- the score is returned as ( x_correct_out_of , y_total)  
score :: Eq a => [a] -> ([a] -> (Int,Int))
score c = flip (,) (length c) . length . filter id . zipWith (==) c

game = score [4,3,5,0]

Comments