Haskell IO method that does nothing

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 nothing is output if it is greater than 100. While the above works, there is a more formal way to return anything other than printing an empty string. eg.

foo :: Int -> IO()
foo a 
   | a > 100 = Nothing
   | otherwise = putStrLn "YES!!!"

      

+3


source to share


2 answers


foo :: Int -> IO ()
foo a 
   | a > 100 = return ()
   | otherwise = putStrLn "YES!!!"

      



+10


source


If you import Control.Monad

, you will access functions when

and unless

, which are of 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 a more preferred form

foo a = unless (a > 100) $ putStrLn "YES!!!"

      

A function unless

is only defined in terms when

like:

unless b m = when (not b) m

      

+6


source







All Articles