gpt4 book ai didi

list - 如何将 all 与 monadic 函数一起使用?

转载 作者:行者123 更新时间:2023-12-02 06:16:36 24 4
gpt4 key购买 nike

我发现自己处于一种情况,我想将 all 与 monadic 函数一起使用。在我看来,这并没有真正变得太漂亮:

f :: Monad m => a -> m Bool

g :: Monad m => [a] -> m Int
g xs = do cnd <- liftM (all (== True)) $ mapM f xs
if cnd
then return 42
else return 0

是否有 Better™ 方法来做到这一点?

最佳答案

如果您导入 Control.ApplicativeData.Bool(如果使用 base >= 4.7),那么您可以将其写为

g xs = bool 0 42 <$> and <$> mapM f xs
-- Or equivalently
-- g xs = bool 0 42 . and <$> mapM f xs
-- g = fmap (bool 0 42 . and) . mapM f

但我认为这不会给您带来很多好处。相反,您还可以将 return 拉到 if-then-else 之外:

g xs = do cnd <- and <$> mapM f xs
return $ if cnd then 42 else 0

甚至

g xs = do ys <- mapM f xs
return $ if and ys then 42 else 0

我认为大多数人会更愿意看到最后两个版本中的一个,尽管最后一个带有“if and foo then bar else baz”的英语人士看起来有点奇怪

关于list - 如何将 all 与 monadic 函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989206/

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