This question already has answers here:
Operating on a return from a Maybe that contains “Just”

(2 个回答)


5年前关闭。




我敢肯定, super 简单,但我似乎找不到答案。我调用了一个返回 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

最佳答案

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

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

关于haskell - 在Maybe中从(Just x)中提取x,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33773155/

10-10 13:43