开发者

Is there a standard function for "do this if Just x"?

开发者 https://www.devze.com 2023-01-30 05:05 出处:网络
I have the following code: doIf :: (a -> IO ()) -> Maybe a -> IO () doIf f x = case x of Just i -> f i

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. (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries? Also, can this be made more generic? I tried replacing IO () with m b but then return () does not work. How do you generically write return () for any monad? (If possible..) Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely? Can I have an operator <#> that applies an argument unless Nothing?

print <#>开发者_C百科; 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 ()


Your doIf is a special case of Data.Foldable.traverse_.

You can usually find this sort of thing through Hoogle, but it seems to be a little broken at the moment. 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 ().


And sure, you can define that operator, it's just (<#>) = doIf (or (<#>) = 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.

(NB: Untested code)

0

精彩评论

暂无评论...
验证码 换一张
取 消