Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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 <#> Just 3
print <#> Nothing

would output

3

But I don't know if this is possible.

like image 338
Steve Avatar asked Nov 28 '22 12:11

Steve


1 Answers

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 ()

like image 161
dino Avatar answered Dec 10 '22 13:12

dino