编写此代码的更短方法
以下模式在 Haskell 代码中经常出现。有没有更短的写法?
if pred x
then Just x
else Nothing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
以下模式在 Haskell 代码中经常出现。有没有更短的写法?
if pred x
then Just x
else Nothing
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
您正在寻找
Control.Monad
中的 >mfilter:请注意,如果条件不依赖于
MonadPlus
的内容,您可以改为编写:You're looking for
mfilter
inControl.Monad
:Note that if the condition doesn't depend on the content of the
MonadPlus
, you can write instead:嗯...您正在寻找一个带有
a
的组合器,一个函数a ->; Bool
并返回一个Maybe a
。停止! 胡格尔时间。没有完全匹配,但find
非常接近:我怀疑您是否真的可以在某处找到您的函数。但为什么不自己定义呢?
Hm... You are looking for a combinator that takes an
a
, a functiona -> Bool
and returns aMaybe a
. Stop! Hoogle time. There is no complete match, butfind
is quite close:I doubt that you can actually find your function somewhere. But why not define it by yourself?
您可以使用
guard
来实现此行为:这是一种非常有用的行为,我什至在我自己的一小套代码中一次性定义了
ensure
(每个人有这样的事情,对吗?You can use
guard
to achieve this behavior:This is such a generally useful behavior that I've even defined
ensure
in my own little suite of code for one-offs (everybody has such a thing, right? ;-):使用:
来自 Data.Bool.HT。
Use:
from Data.Bool.HT.
有了上面的定义,你可以简单地写:
当然,这与 Daniel Wagner 的
ensure
或 FUZxxl 的ifMaybe
没有什么不同。但它的名称很简单f
,使其成为最短的,并且它的定义正是您给出的代码,使其成为最容易证明正确的代码。 ;)一些 ghci,只是为了好玩
如果你不能告诉,这不是一个非常严肃的答案。其他人更有洞察力,但我无法抗拒半开玩笑的回应“让这段代码更短”。
Given the above definition, you can simply write:
Of course this is no different than Daniel Wagner's
ensure
or FUZxxl'sifMaybe
. But it's name is simplyf
, making it the shortest, and it's definition is precisely the code you gave, making it the most easily proven correct. ;)Some ghci, just for fun
If you couldn't tell, this isn't a very serious answer. The others are a bit more insightful, but I couldn't resist the tongue-in-cheek response to "make this code shorter".
通常我是非常通用的代码的忠实粉丝,但实际上我发现这个确切的函数非常有用,专门用于
Maybe
,我保留它而不是使用guard
、mfilter
等。我使用的名称是
justIf
,我通常使用它来执行以下操作:基本上,需要在复合表达式中完成某种按元素过滤或检查的内容,所以用
Maybe
来表示谓词的结果。对于像这样的专门版本,您实际上无法做太多事情来缩短它。这已经很简单了。简洁和只是为了字符数而敲代码之间有一条微妙的界限,对于这么简单的事情,我真的不会担心尝试“改进”它......
Usually I'm a big fan of very generic code, but I actually find this exact function useful often enough, specialized to
Maybe
, that I keep it around instead of usingguard
,mfilter
, and the like.The name I use for it is
justIf
, and I'd typically use it for doing things like this:Basically, stuff where some sort of element-wise filtering or checking needs to be done in a compound expression, so
Maybe
is used to indicate the result of the predicate.For the specialized version like this, there really isn't much you can do to make it shorter. It's already pretty simple. There's a fine line between being concise, and just golfing your code for character count, and for something this simple I wouldn't really worry about trying to "improve" it...