在 Maybe 中从 (Just x) 中提取 x

Extracting x from (Just x) in a Maybe

我确定非常简单,但我似乎找不到答案。我调用了一个 returns Maybe x 的函数,我想看到 x。如何从我的 Just x 响应中提取 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

有一个带有此签名的标准函数,fromJust

使用 Hoogle 进行这样的搜索,it's a wonderful tool

惯用的方式是模式匹配。

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

您也可以使用 fromMaybe,它采用默认值。

fromMaybe "Nothing to see here..." (Just "I'm real!")