I would like to ask if you know what this function does:
hasUnassigned :: [Int] -> Bool
hasUnassigned board = isJust $ elemIndex 0 board
I found this function online and I plan to use it to help draw Sudoku game solutions.
Please could you explain to me how it works?
elemIndex
searches for the first argument in the second argument, which is a list. It returns a Maybe Int
- Just
the index if the element is found, Nothing
otherwise.
isJust
returns true if a Maybe
value is a Just
, false if it is a Nothing
.
In other words, this is a very awkward way of testing whether board
contains 0. A better way is
hasUnassigned board = 0 `elem` board
elemIndex
has signature a -> [a] -> Maybe Int
. When applied to x
and a list list
, it gives us Just i
if x
appears for the first time in list
at position i
. If x
is not in list
, we get Nothing
instead.
The outer function, isJust
, takes a Maybe a
and tells us if it's of the form Just whatever
or Nothing
. hasUnassigned
thus checks to see if there's a 0
in the board list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With