Here is my code:
foo :: Int -> IO()
foo a
| a > 100 = putStr ""
| otherwise = putStrLn "YES!!!"
The function should output "YES!!!" if it is less than 100 and output nothing if it is more than 100. Although the above works, is there a more formal way to return nothing other than printing an empty string. e.g.
foo :: Int -> IO()
foo a
| a > 100 = Nothing
| otherwise = putStrLn "YES!!!"
foo :: Int -> IO ()
foo a
| a > 100 = return ()
| otherwise = putStrLn "YES!!!"
If you import Control.Monad
, you'll have access to the when
and unless
functions, which have the types
when, unless :: Monad m => Bool -> m () -> m ()
And can be used in this case as
foo a = when (not $ a > 100) $ putStrLn "YES!!!"
Or the more preferred form
foo a = unless (a > 100) $ putStrLn "YES!!!"
The unless
function is just defined in terms of when
as:
unless b m = when (not b) m
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With