Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Haskell Data.Maybe function do?

Tags:

haskell

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?

like image 945
user1885332 Avatar asked Dec 11 '22 14:12

user1885332


2 Answers

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
like image 117
Sebastian Redl Avatar answered Dec 14 '22 03:12

Sebastian Redl


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.

like image 28
gspr Avatar answered Dec 14 '22 03:12

gspr