在Haskell中将Maybe Int转换为Int [英] Convert Maybe Int to Int in Haskell
问题描述
我正在研究下面的代码,并希望找到框中的数字的索引字符串。所以我用findIndex,但它返回Maybe Int值,而我只想要Int值。
如何将Maybe Int转换为Int值或者有什么方法可以从Maybe Int中提取Int。如果Maybe Int没有任何东西,那么代码应该会打印一条错误消息
box :: String
box = unlines $ [ 0 | 1 | 2,
---------,
3 | 4 | 5,
--------- ,
6 | 7 | 8]
moves = do
putStrLn输入数字
数字< - readLn :: IO Int
打印号码
findpostion号码框
findposition number box = findIndex(== number)box
$ b $您可以使用 do
语句中的模式匹配轻松完成此操作: $ b
$ b
case
的findposition数字框Just n - > - 用n
做任何事 - > putStrLn无效的号码! - 你可以处理你想要的错误。
一个好的选择是创建一个单独的IO操作来获取数字:
getNumber = do putStrLn输入数字:
number< - readLn
case $ b $的findposition number box b只是n - > - 做任何
Nothing - > putStrLn请重试。 >> getNumber
这样,如果用户输入一个无效的数字,它就会再次提示。
此外,正如现在写的,您的代码将无法工作。你应该有一些其他的方式将数字存储在 box
中作为实际数字;现在,他们在Strings中。
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 value.
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"]
moves = do
putStrLn " Enter the number"
number <- readLn :: IO Int
print number
findpostion number box
findposition number box = findIndex (==number) box
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.
这篇关于在Haskell中将Maybe Int转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!