Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell IO method that does nothing

Tags:

io

haskell

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!!!"
like image 517
Yahya Uddin Avatar asked Dec 03 '22 18:12

Yahya Uddin


2 Answers

foo :: Int -> IO ()
foo a 
   | a > 100 = return ()
   | otherwise = putStrLn "YES!!!"
like image 88
Tom Ellis Avatar answered Dec 29 '22 21:12

Tom Ellis


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
like image 37
bheklilr Avatar answered Dec 29 '22 20:12

bheklilr