Convert Maybe Int to Int in Haskell

后端 未结 2 1430
温柔的废话
温柔的废话 2021-02-15 13:59

I am working on the following 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 v

相关标签:
2条回答
  • 2021-02-15 14:37

    Obviously, it's not possible in general: when the search doesn't succeed there is no canonical integer return value, so you get a Nothing without any such value then.

    If you don't really care about the Nothing case (e.g. because you will always make sure there is one such element) you can use the fromJust function out of Data.Maybe, which you can also quickly implement yourself:

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

    However that's not really recommendable because you will need to make sure this doesn't break, and doing this is much easier by means of a proper pattern matching.

    0 讨论(0)
  • 2021-02-15 14:55

    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.

    Also, as written now, your code won't work. You should have some other way of storing the numbers in box as actual numbers; right now, they're in Strings.

    0 讨论(0)
提交回复
热议问题