超级简单我很确定,但我似乎无法找到答案。我调用一个返回Maybe x
的函数,我希望看到x
。如何从x
回复中提取Just x
?
seeMyVal :: IO ()
seeMyVal = do
if getVal == Nothing
then do
putStrLn "Nothing to see here"
else do
putStrLn getVal -- what do I have to change in this line?
getVal :: (Maybe String)
getVal = Just "Yes, I'm real!"
这会引发错误:
Couldn't match type ‘Maybe String’ with ‘[Char]’
Expected type: String
Actual type: Maybe String
In the first argument of ‘putStrLn’, namely ‘getVal’
In a stmt of a 'do' block: putStrLn getVal
答案 0 :(得分:19)
惯用的方式是模式匹配。
seeMyVal = case getVal of
Nothing -> putStrLn "Nothing to see here"
Just val -> putStrLn val
如果您愿意,可以将putStrLn
视为:
seeMyVal = putStrLn $ case getVal of
Nothing -> "Nothing to see here"
Just val -> val
答案 1 :(得分:9)
您也可以使用fromMaybe,这是默认设置。
fromMaybe "Nothing to see here..." (Just "I'm real!")
答案 2 :(得分:2)
此签名有一个标准函数fromJust
。
使用Hoogle进行此类搜索,it's a wonderful tool。