haskell - Need a basecase for returning position in a list -
haskell - Need a basecase for returning position in a list -
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
blank returns first position nothing
. if not nothing
, homecoming reasonable, not error! how that?
output:
main> blank illustration (0,2) main> blank sud *** exception: prelude.(!!): index big
(sud contains no nothing)
example = sudoku [ [just 3, 6, nothing, nothing, 7, 0, 2, nothing, nothing] , [nothing, 5, nothing, nothing, nothing, nothing, 1, 8, nothing] , [nothing, nothing, 9, 2, nothing, 4, 7, nothing, nothing] , [nothing, nothing, nothing, nothing, 1, 3, nothing, 2, 8 ] , [just 4, nothing, nothing, 5, nothing, 2, nothing, nothing, 9 ] , [just 2, 7, nothing, 4, 6, nothing, nothing, nothing, nothing] , [nothing, nothing, 5, 3, nothing, 8, 9, nothing, nothing] , [nothing, 8, 3, nothing, nothing, nothing, nothing, 6, nothing] , [nothing, nothing, 7, 6, 9, nothing, nothing, 4, 3 ] ]
(!! 0)
head
, head
works on non-empty lists, need check whether case:
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)
this of course of study much ill-advised; should homecoming position wrapped in maybe (i.e. either just (y,x)
or nothing
) type of function changes blank :: sudoku -> maybe pos
. utilize built-in function listtomaybe
data.maybe
:
so that
blankmaybe :: sudoku -> maybe pos blankmaybe (sudoku rs) = listtomaybe [(y,x) | (r,y) <- rs `zip` [0..8] , (c,x) <- r `zip` [0..8] , c == nothing]
or utilize take 1
instead of head
, blankhead :: sudoku -> [pos]; blankhead (sudoku rs) = take 1 [(y,x) | ..... ]
. using maybe
best choice, type corresponds our intent here.
list haskell sudoku
Comments
Post a Comment