gpt4 book ai didi

如果两个参数都是 Just ,则 Haskell 函数返回 Just 值对,否则返回任何值

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

Define a function

   pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)

that produces a Just result only if both arguments are Just, and a Nothing if either argument is Nothing.



我想出了:
pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe (Just a) Nothing = Nothing
pairMaybe Nothing (Just b) = Nothing

我不确定这是否是正确的写作方式。这有什么问题吗,或者这是定义这个函数的方式吗?

另外我想我可能想要更好地解释这个函数实际上可以做什么,所以如果我调用 pairMaybe有两个参数,它们可以是什么参数?当然,它们必须是 Maybe 类型的,但什么是一个很好的例子?

最佳答案

通过模式匹配来做到这一点很好;你可以通过使用来简化你的代码

pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)
pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe _ _ = Nothing

话虽如此,您的函数实际上只是解除了 (,)函数(创建 2 元组)到 Maybe monad,所以你也可以写
pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)
pairMaybe = liftM2 (,)

关于如果两个参数都是 Just ,则 Haskell 函数返回 Just 值对,否则返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20294098/

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