Haskell Coding Dojo 20090428
Our code from the Haskell Coding Dojo - 28th April 2009
MastermindTests.hs
module Main where
import Test.HUnit
import Mastermind
tests = TestList
[
"one hole match" ~: score "R" "R" ~?= [Black]
, "one hole no match" ~: score "R" "B" ~?= []
, "two holes all match" ~: score "RB" "RB" ~?= [Black, Black]
, "two holes one matches" ~: score "RR" "RB" ~?= [Black]
, "two holes one partial match" ~: score "RB" "GR" ~?= [White]
, "two holes swapped" ~: score "RB" "BR" ~?= [White, White]
, "three holes one partial" ~: score "RBB" "GRR" ~?= [White]
, "three holes one partial again" ~: score "GRR" "RBB" ~?= [White]
]
main = runTestTT tests
Mastermind.hs (initial version)
module Mastermind where
import Data.List
data ScorePin = Black | White
deriving (Eq, Ord, Show)
score secret guess = blackPins ++ whitePins
where
blackPins = blacks secret guess
whitePins = whites secret guess
blacks secret guess =
[Black | (s, g) <- (zip secret guess), s == g]
whites secret guess =
notBadGuesses secret' guess'
where (secret', guess') = notBlack secret guess
notBadGuesses [] _ = []
notBadGuesses (x:xs) guesses
| elem x guesses = (White : notBadGuesses xs (delete x guesses))
| otherwise = notBadGuesses xs guesses
notBlack secret guess =
unzip [(s, g) | (s, g) <- (zip secret guess), s /= g]
Mastermind.hs (refactored version)
module Mastermind where
import Data.List
data ScorePin = Black | White deriving (Eq, Ord, Show)
score secret guess = blacks ++ whites where (secret', guess') = unzip [(s, g) | (s, g) <- zip secret guess, s /= g] countWhites = length secret' - length (secret' \\ guess') countBlacks = length secret - length secret' blacks = replicate countBlacks Black whites = replicate countWhites White
geo news
|