Convert Int Int Int to Haskell possible

I am working on the following code and would like to find the index of the number in the string. So I used findIndex, but it returns Maybe Int value, whereas I want only Int value.

How can I convert Maybe Int to Int, or is there a way I can extract Int from Maybe Int. The code should print an error message if Maybe Int is nothing

box:: String box = unlines $ ["0 | 1 | 2", "---------", "3 | 4 | 5", "---------", "6 | 7 | 8"] moves = do putStrLn " Enter the number" number <- readLn :: IO Int print number findpostion number box findposition number box = findIndex (==number) box 
+6
source share
2 answers

You can easily do this using the pattern matching in the do statement:

 case findposition number box of Just n -> -- do whatever with n Nothing -> putStrLn "Invalid number!" -- you can handle the error however you want. 

A good option would be to create a separate I / O action to get the number:

 getNumber = do putStrLn "Enter the number:" number <- readLn case findposition number box of Just n -> -- Do whatever Nothing -> putStrLn "Please try again." >> getNumber 

Thus, if the user enters an invalid number, he simply requests again.

Also, as written now, your code will not work. You should have another way of storing the numbers in the box as actual numbers; right now, they are in Rows.

+16
source

Obviously, this is not possible at all: when the search is not performed, there is no canonical integer value, so you get Nothing without that value.

If you really don't need the Nothing case (for example, because you always make sure that there is one such element), you can use the fromJust function from Data.Maybe , which you can also quickly implement yourself:

 findposition number = (\(Just i)->i) . findIndex (==number) 

However, this is not recommended, because you will need to make sure that it does not break, and it is much easier to do this with appropriate pattern matching.

+10
source

Source: https://habr.com/ru/post/906264/


All Articles