Created
May 28, 2014 18:32
-
-
Save jdiez17/8b0384e99ddfbaa09d95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Sudoku where | |
| import Control.Monad (sequence) | |
| data Digit = D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9 | |
| deriving (Eq, Ord, Read, Enum) | |
| mkDigit :: Int -> Maybe Digit | |
| mkDigit n | |
| | n > 0 && n < 10 = Just $ toEnum (n-1) | |
| | otherwise = Nothing | |
| instance Show Digit where show x = show $ fromEnum x+1 | |
| newtype Sudoku = Sudoku { toList :: [[Digit]] } | |
| deriving (Show) | |
| mkSudoku :: [[Int]] -> Maybe Sudoku | |
| mkSudoku xss = if isSudoku then buildSudoku else Nothing | |
| where | |
| isSudoku :: Bool | |
| isSudoku = outerLength == 9 && (all (== outerLength) $ map length xss) | |
| where outerLength = length xss | |
| toDigits :: Maybe [[Digit]] | |
| toDigits = let listOfMaybes = [map mkDigit y | y <- xss] | |
| in sequence . map sequence $ listOfMaybes | |
| buildSudoku :: Maybe Sudoku | |
| buildSudoku = let (Just digits) = toDigits | |
| in Just $ Sudoku digits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment