2014-10-09 55 views
1
data Sudoku = Sudoku [[Maybe Int]] 

blank :: Sudoku -> Pos 
blank (Sudoku rs) = [(y,x) | (r,y) <- rs `zip` [0..8], (c,x) <- r `zip` [0..8], c == Nothing] !! 0 

空白返回的第一個位置是Nothing。如果它不是Nothing,我想返回一些合理的,而不是錯誤!我怎麼能這樣做?需要一個返回列表中的位置的基準點

輸出:

Main> blank example 
(0,2) 

Main> blank sud 
*** Exception: Prelude.(!!): index too large 

(SUD包含什麼都沒有)

example = 
    Sudoku 
     [ [Just 3, Just 6, Nothing, Nothing, Just 7, Just 0, Just 2, Nothing, Nothing] 
     , [Nothing, Just 5, Nothing, Nothing, Nothing, Nothing, Just 1, Just 8, Nothing] 
     , [Nothing, Nothing, Just 9, Just 2, Nothing, Just 4, Just 7, Nothing, Nothing] 
     , [Nothing, Nothing, Nothing, Nothing, Just 1, Just 3, Nothing, Just 2, Just 8 ] 
     , [Just 4, Nothing, Nothing, Just 5, Nothing, Just 2, Nothing, Nothing, Just 9 ] 
     , [Just 2, Just 7, Nothing, Just 4, Just 6, Nothing, Nothing, Nothing, Nothing] 
     , [Nothing, Nothing, Just 5, Just 3, Nothing, Just 8, Just 9, Nothing, Nothing] 
     , [Nothing, Just 8, Just 3, Nothing, Nothing, Nothing, Nothing, Just 6, Nothing] 
     , [Nothing, Nothing, Just 7, Just 6, Just 9, Nothing, Nothing, Just 4, Just 3 ] 
     ] 
+0

可能您可以爲輸入添加預期輸出的示例? – Sibi 2014-10-09 12:27:05

+5

如何返回'Maybe Pos'呢? – MathematicalOrchid 2014-10-09 12:33:54

+0

剛剛添加的信息。不,任務說我應該返回一個Pos .. – Josu24 2014-10-09 12:45:53

回答

2

(!! 0)head,但head只適用於非空列表,所以你需要檢查這是否是案例

blank :: Sudoku -> Pos 
blank (Sudoku rs) = case [(y,x) | (r,y) <- rs `zip` [0..8] 
           , (c,x) <- r `zip` [0..8] 
           , c == Nothing] 
        of (pos:_) -> pos; _ -> (-1, -1) 

這當然是非常不明智的;您應該返回包含在Maybe中的位置(即Just (y,x)Nothing),以便函數的類型更改爲blank :: Sudoku -> Maybe Pos。然後,你從Data.Maybe使用內置函數listToMaybe

 
Prelude> :m +Data.Maybe 
Prelude Data.Maybe> listToMaybe [1..5] 
Just 1 
Prelude Data.Maybe> listToMaybe [] 
Nothing 

使

blankMaybe :: Sudoku -> Maybe Pos 
blankMaybe (Sudoku rs) = listToMaybe [(y,x) | (r,y) <- rs `zip` [0..8] 
              , (c,x) <- r `zip` [0..8] 
              , c == Nothing] 

或者你可以使用take 1代替head,與blankHead :: Sudoku -> [Pos]; blankHead (Sudoku rs) = take 1 [(y,x) | ..... ]。但使用Maybe是最好的選擇,因爲這種類型完全符合我們的意圖。

相關問題