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

Mar*_*van 4 haskell types maybe

超级简单我敢肯定,但我似乎无法找到答案.我调用一个返回的函数,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!"
Run Code Online (Sandbox Code Playgroud)

这会引发错误:

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
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 19

惯用的方式是模式匹配.

seeMyVal = case getVal of
    Nothing  -> putStrLn "Nothing to see here"
    Just val -> putStrLn val
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你可以考虑putStrLn出来:

seeMyVal = putStrLn $ case getVal of
    Nothing  -> "Nothing to see here"
    Just val -> val
Run Code Online (Sandbox Code Playgroud)


rob*_*ong 9

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

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