2012-01-18 128 views
6

我正在研究以下代码,并希望找到该字符串中数字的索引。所以我用findIndex,但它返回Maybe Int值,而我只想要Int值。在Haskell中将Maybe Int转换为Int

我该如何将Maybe Int转换为Int值或者有没有什么方法可以从Maybe Int中提取Int。该代码应打印错误信息,如果可能int是什么

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 

回答

16

您可以轻松地做到这一点使用模式匹配您的do声明:

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

一个很好的选择是创建一个单独的IO动作得到号码:

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

这样如果用户输入一个无效号码,它只是再次询问。

此外,正如现在写的,您的代码将无法工作。您应该有其他方式将box中的数字存储为实际数字;现在,他们在Strings中。

+0

其实,其目的是要找到用户输入的号码,稍后用任何其他字符替换它说'x' – 2012-01-18 05:03:54

+0

啊。在这种情况下,由于您正在查看字符串,因此您需要读入“Char”而不是“Int”。实际上,你应该完全可以忽略':: IO Int'位。 – 2012-01-18 05:06:40

+0

好的,谢谢..我会试试这个,一定会回复你... – 2012-01-18 05:09:52

10

很显然,这是不可能的一般:当搜索不成功没有规范的整数返回值,所以你得到一个Nothing没有任何这样的值然后。

如果你真的不关心Nothing情况下(例如,因为你永远确保有一个这样的元素),你可以使用fromJust功能出Data.Maybe,你也可以快速实现自己:

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

但是这并不是真的值得推荐,因为你的需要确保这不会中断,并通过适当的模式匹配来做到这一点更容易。

+0

他提到他想在“Nothing”上“返回错误信息”。虽然这有些模糊,但我认为只要打印错误而不是让程序崩溃,他会很高兴。 – 2012-01-18 05:48:35

+4

如果在你正在工作的上下文中有*是一个“规范整数”,那么你可以在'canonicalInt :: Int'和'maybeVal :: Maybe Int'中使用'fromMaybe canonicalInt maybeVal'。请参阅[Data.Maybe文档](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Maybe.html#v:fromMaybe) – 2012-01-18 06:50:19