IO ()) -> Maybe a -> IO () doIf fx = case x of Jus...">

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

I have the following code:

doIf :: (a -> IO ()) -> Maybe a -> IO () doIf fx = case x of Just i -> fi Nothing -> return () main = do mapM_ (doIf print) [Just 3, Nothing, Just 4] 

which outputs:

 3 4 

In other words, Just values ​​print, but Nothing causes no action. (And don't interrupt the calculations.)

Is there such a standard feature in Haskell libraries? Also, could this be more general? I tried replacing IO () with mb , but then return () does not work. How do you write return () for any monad? (If possible ..) Could Maybe be generalized here?

Finally, can I completely remove the doIf function? Can I have a <#> operator that applies an argument if Nothing ?

 print <#> Just 3 print <#> Nothing 

displays

 3 

But I do not know if this is possible.

+4
source share
3 answers

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

You can usually find such a thing through Hoogle , but it seems to be a bit broken at the moment. The command line version that I installed on my system gives Data.Foldable.traverse_ as the first result for the query (a -> IO ()) -> Maybe a -> IO () .


And of course, you can define this statement simply (<#>) = doIf (or (<#>) = Data.Foldable.traverse_ ).

+7
source

Take a look at the function:

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

You almost wrote it in doIf , except for the fixed return ()

+17
source

Could you do something line by line:

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

See the documentation for catMaybes .

(NB: unverified code)

+5
source

Source: https://habr.com/ru/post/1332055/


All Articles