我正在编写以下代码,并希望找到框字符串中数字的索引。所以我用了findIndex
但它返回Maybe Int
值,而我只想要Int
value.
我怎样才能转换Maybe Int
to Int
值或者有什么方法可以提取Int
from Maybe Int
。如果出现以下情况,代码应打印一条错误消息: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
您可以使用模式匹配轻松地做到这一点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 中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)