gpt4 book ai didi

haskell - Haskell 中的通用 'unwrap' 函数?

转载 作者:行者123 更新时间:2023-12-01 16:23:20 25 4
gpt4 key购买 nike

当我对某个值使用 fmap 时,它本质上是“拆箱”该值,将函数应用于它,然后将其装箱。

例如:

-- returns Just 8
fmap (+3) (Just 5)

是否有任何函数可以为我提供值而不将其装箱备份?

-- returns 8
fmap_2 (+3) (Just 5)

当然,我不知道这对于数组如何工作,但对于初学者来说,它对于EitherMaybe很有用。我还可以用它来轻松混合 Monad:

-- myfunc :: Maybe Int

-- if myfunc returned a Just, show it and then print it. Otherwise, print 'Nothing'.
putStrLn . fmap show $ myfunc

或者还有另一种混合 Monad 的标准方法吗?

最佳答案

要提取Maybe,请使用maybe:

maybe 0 (+3) $ Just 5
>>> 8
maybe 0 (+3) Nothing
>>> 0

仅当收到 Nothing 必须被视为异常情况时,才应使用 fromJust。如果没有充分的理由,不要养成让程序崩溃的习惯。 也许要么 正是为了帮助您避免这种情况。

对于Either,有一个函数either:

either (*2) (+2) $ Left 3
>>> 6
either (*2) (+2) $ Right 3
>>> 5

请注意,在正确的代码中,您不需要经常提取 monad。这就是它们的全部要点,Haskell 必须提供您可能需要的所有工具来处理一元值,就像它们被提取一样。

关于haskell - Haskell 中的通用 'unwrap' 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9461053/

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