简体   繁体   English

是否有标准功能“如果只是x,请执行此操作”?

[英]Is there a standard function for “do this if Just x”?

I have the following code: 我有以下代码:

doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]

which outputs: 哪个输出:

3
4

In other words, the Just values are printed, but Nothing values cause no action. 换句话说, Just值被打印,但Nothing值不会导致任何操作。 (And do not interrupt computation.) (并且不要中断计算。)

Is there a standard function like this in the Haskell libraries? 在Haskell库中是否有这样的标准函数? Also, can this be made more generic? 此外,这可以更通用吗? I tried replacing IO () with mb but then return () does not work. 我尝试用mb替换IO ()但是然后return ()不起作用。 How do you generically write return () for any monad? 你如何为任何monad一般写return () (If possible..) Can even the Maybe be generalized here? (如果可能..)甚至可以将Maybe推广到这里?

Lastly, can I do away with the doIf function entirely? 最后,我可以完全doIf功能吗? Can I have an operator <#> that applies an argument unless Nothing ? 我可以有一个运算符<#>,除非Nothing

print <#> Just 3
print <#> Nothing

would output 会输出

3

But I don't know if this is possible. 但我不知道这是否可行。

Take a look at the function: 看看这个功能:

maybe :: b -> (a -> b) -> Maybe a -> b

You've almost written it in doIf except for the fixed return () 你几乎把它写在doIf除了固定的return ()

Your doIf is a special case of Data.Foldable.traverse_ . 您的doIfData.Foldable.traverse_

You can usually find this sort of thing through Hoogle , but it seems to be a little broken at the moment. 你通常可以通过Hoogle找到这种东西,但此刻它似乎有点破碎。 The command-line version I have installed on my system gives Data.Foldable.traverse_ as the first result for the query (a -> IO ()) -> Maybe a -> IO () . 我在系统上安装的命令行版本将Data.Foldable.traverse_作为查询的第一个结果(a -> IO ()) -> Maybe a -> IO ()


And sure, you can define that operator, it's just (<#>) = doIf (or (<#>) = Data.Foldable.traverse_ ). 当然,您可以定义该运算符,它只是(<#>) = doIf (或(<#>) = Data.Foldable.traverse_ )。

Could you do somthing along the lines of: 你可以做的事情是这样的:

main = do
  mapM_ print $ catMaybes [Just 3, Nothing, Just 4]

See the documentation for catMaybes . 请参阅catMaybes的文档。

(NB: Untested code) (注意:未经测试的代码)

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

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