简体   繁体   English

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

[英]Haskell function returning Just pair of values if both arguments are Just, Nothing otherwise

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 . 只有当两个参数都是Just时才产生Just结果,如果两个参数都是Nothing则产生Nothing

I've come up with: 我想出来:

pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe (Just a) Nothing = Nothing
pairMaybe Nothing (Just b) = Nothing

I'm not sure if this is the right way of writing it. 我不确定这是否是正确的写作方式。 Is there something wrong with this or is this the way to define this function? 这有什么问题或者这是定义这个功能的方法吗?

Also I think I'd probably like a better explanation of what this function can actually do , so if I called pairMaybe with two arguments, what arguments can they be? 另外我想我可能想要更好地解释这个函数实际上可以做什么 ,所以如果我用两个参数调用pairMaybe ,它们可以是什么参数? Of course they have to be of type Maybe , but what's a good example? 当然,他们必须属于Maybe类型,但有什么好例子?

Doing this via pattern matching is fine; 通过模式匹配来做这件事很好; you could simplify your code though by using 你可以通过使用来简化你的代码

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

That being said, your function actually just lifts the (,) function (which creates 2-tuples) into the Maybe monad, so you could also write 话虽这么说,你的函数实际上只是将(,)函数(创建2元组)提升到Maybe monad中,所以你也可以写

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

You missed the pattern where both values are Nothing (that won't match to any of your patterns): 您错过了两个值都为Nothing (与您的任何模式都不匹配)的模式:

pairMaybe Nothing Nothing = Nothing

Other than that pattern matching is a great way of getting things done in Haskell. 除了模式匹配之外,还有一种在Haskell中完成工作的好方法。

Looks great! 看起来很棒! Though you can shorten it a bit. 虽然你可以缩短一点。

pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe _        _        = Nothing

This also fixes the bug Simeon pointed out. 这也修复了Simeon指出的错误。 The reason you can simplify it like that is that all the right hand sides with Nothing are the same, so those cases can be merged into one. 您可以简化它的原因是Nothing所有右侧都是相同的,因此这些案例可以合并为一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM