Haskell IO方法什么都不做

Yah*_*din 3 io haskell

这是我的代码:

foo :: Int -> IO()
foo a 
   | a > 100 = putStr ""
   | otherwise = putStrLn "YES!!!"
Run Code Online (Sandbox Code Playgroud)

该功能应输出"YES !!!" 如果它小于100并且如果它大于100则不输出任何内容.虽然上面有效,但除了打印空字符串之外,还有更正式的方法来返回任何内容.例如

foo :: Int -> IO()
foo a 
   | a > 100 = Nothing
   | otherwise = putStrLn "YES!!!"
Run Code Online (Sandbox Code Playgroud)

Tom*_*lis 10

foo :: Int -> IO ()
foo a 
   | a > 100 = return ()
   | otherwise = putStrLn "YES!!!"
Run Code Online (Sandbox Code Playgroud)


bhe*_*ilr 6

如果导入Control.Monad,您将可以访问具有类型的whenunless函数

when, unless :: Monad m => Bool -> m () -> m ()
Run Code Online (Sandbox Code Playgroud)

并且可以在这种情况下用作

foo a = when (not $ a > 100) $ putStrLn "YES!!!"
Run Code Online (Sandbox Code Playgroud)

或者更优选的形式

foo a = unless (a > 100) $ putStrLn "YES!!!"
Run Code Online (Sandbox Code Playgroud)

unless函数仅根据以下内容定义when:

unless b m = when (not b) m
Run Code Online (Sandbox Code Playgroud)