Pages

Thursday, May 19, 2011

Convert Maybe Int to Int value in Haskell


I was working on some code and wanted to find the index of the number in the box string. So i used findIndex but it returns the Maybe Int value whereas i want only Int value.

So the question that arises is how can i convert Maybe Int to Int value or is there any way in which 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"]


You can easily do this using pattern matching in your 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 IO 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


This way if the user enters an invalid number, it just asks again.