2014-10-16 25 views
-1

這些代碼段有關我的問題:非詳盡的誤差函數

type Pos = (Int, Int) 
type Block = [Maybe Int] 
type Sudoku = [[Maybe Int]] 

blank :: Sudoku -> Pos 
blank sud = let k = ((whichRow sud) -1) in 
      let n = ((whereIsNothing (head (drop (k-1) (rows sud)))) -1) in 
      (k, n) 


whichRow :: Sudoku -> Int 
whichRow sud = whichRow' sud 0 
    where 
    whichRow' (Sudoku [])  i = i 
    whichRow' (Sudoku (r:rs)) i = if isNothingPresent r 
     then 1 
     else whichRow' (Sudoku rs) (i+1) 


whereIsNothing :: Block -> Int 
whereIsNothing (x:xs) = if x == Nothing then 1 else 1 + whereIsNothing xs 


isNothingPresent :: Block -> Bool 
isNothingPresent b = not (Nothing `notElem` b) 

我想在這裏做的是,與空白,在數獨是空返回的位置(意思是它的元素是沒有)。由於習慣上從0開始計數,這是空白函數中的-1。 (Int, Int)類型表示(行號,元素號)。哪一行有空單元格,哪一行元素包含空單元格。

如果我用第一個'行'中的'空白'單元劃掉它,我會得到預期的結果。但是,如果空單元位於第一行的其他位置,我會得到一個非詳盡的錯誤。很確定whereIsNothing函數是原因,沒有basecase。我無法弄清楚如何解決它。有任何想法嗎?

編輯:當我寫的數獨一個有效的解決方案,而第二排爲Nothing在變化的值,我得到錯誤信息:

*Main> blank example2 
(0,*** Exception: Sudoku.hs:166:1-73: Non-exhaustive patterns in function whereIsNothing 

那麼,該函數返回的第一個數字爲1,它將其作爲零返回。

+1

'whereIsNothing':如果列表爲空,會發生什麼?順便說一句,'isNothingPresent'就是'any(== Nothing)'。 – Zeta 2014-10-16 11:50:58

+0

@Zeta我試圖以一種只有在沒有任何東西存在時才調用whereIsNothing的方式來設計我的空白函數。我不確定我將如何處理一個空列表作爲該函數的一個參數。 – Rewbert 2014-10-16 12:33:01

+0

@Rewbert你可以改變'whereIsNothing :: Block - > Maybe Int',然後*拉*它一直通過(你會看到你的大部分函數確實是部分的 - 例如,如果'blank'返回任何東西)*〜Luke〜:讓這些類型指導你!* – Carsten 2014-10-16 12:57:59

回答

1

首先,如果你想解決數獨,你可能更喜歡某種代數簡化:而不是使用[[Maybe Int]],您可以使用[[[Maybe Bool]]],由他們代表的可能性從1-9的數字(即Just 8變成`[只是假的,只是假的,只是假的,只是假的,只是假的,只是假的,只是假的,只是真的,只是假的])。那麼,你已經有了像以前一樣的行和列,而且文件基於對Sudoku添加了新的「深度」。正常的數獨規則變爲:每行必須有一個True,每列只有一個True,每個文件只有一個True,每個「塊」的每個深度只有一個True。

其次,你正在做的所有事情都是通過庫函數來解決的。特別是:

import Data.Maybe (isNothing, listToMaybe) 

allpositions :: [Pos] 
allpositions = [(x, y) | x <- [1..9], y <- [1..9]]  

getValue :: Sudoku -> Pos -> Maybe Int 
getValue s (x, y) = s !! x !! y 

blank :: Sudoku -> Maybe Pos 
blank s = listToMaybe $ filter (isNothing . getValue s) allpositions 

這裏listToMaybe是一個標準庫函數,它是像head但當名單[]它不會破壞(這樣你就可以趕上在沒有空格離開的情況下,你已處理完畢解決數獨問題!)你可能更喜歡簡單地保留空白位置的列表。