gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:48:32 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

最佳答案

惯用的方法是模式匹配。

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com