简体   繁体   中英

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. (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 mb 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 <#> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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