我遇到了这个问题:
Couldn't match expected type ‘Int’ with actual type ‘Maybe Int’
我能以某种方式将“Maybe Int”转换为“Int”吗??
if index == Nothing
then
do
let index = 0
putStrLn(fancyPrint2 $ kaasasOlevList !! index)
else
do
let index = index
putStrLn(fancyPrint2 $ kaasasOlevList !! index)
我这样试过,但这给了我:
Exception: <<loop>>
最佳答案
你有几种不同的选择来解决这个问题
首先是使用您的 if
语句,但稍作修改(尽管避免这样做)
if index == Nothing
then
do
let index' = 0
putStrLn $ fancyPrint2 $ kaasasOlevList !! index'
else
do
let (Just index') = index
putStrLn $ fancyPrint2 $ kaasasOlevList !! index'
我在这里写 index'
,因为 Haskell 不允许您覆盖现有变量,但是它允许您隐藏它们。但一般来说,更好的做法是在变量的“修改”版本末尾加上“素数”符号 ('
)。这样您就可以在需要时随时访问原件。
其次,您可以使用 case
表达式将您的代码转换为
case index of
Just i -> putStrLn $ fancyPrint2 $ kaasasOlevList !! i
Nothing -> putStrLn $ fancyPrint2 $ kaasasOlevList !! 0
或者,如果您使用 where
子句稍微清理一下:
case index of
Just i -> putIndex i
Nothing -> putIndex 0
where putIndex x = putStrLn $ fancyPrint2 $ kaasasOlevList !! x
最后还有 fromMaybe
可以让你这样做:
import Data.Maybe (fromMaybe)
-- ...
do
let index' = fromMaybe 0 index
putStrLn $ fancyPrint2 $ kaasasOlevList !! index'
你也可以使用守卫。但是看到我不知道你的代码片段来自哪里,我不知道使用守卫是否合理。
您可以阅读更多关于守卫、case 表达式和模式匹配的信息 here
关于Haskell 可能输入 -> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622265/