Haskell中有when
和unless
的组合函数,它们是Control.Monad模块中的函数。这些函数用于根据特定的条件执行操作。
when
函数接受一个布尔表达式和一个操作,如果布尔表达式为真,则执行该操作;否则,不执行任何操作。
unless
函数与when
函数相反,当布尔表达式为假时执行操作。
这些函数的定义如下:
when :: Monad m => Bool -> m () -> m ()
when p s = if p then s else return ()
unless :: Monad m => Bool -> m () -> m ()
unless p s = if not p then s else return ()
这些函数在编写条件逻辑时非常有用,可以简化代码并提高可读性。
以下是一些使用when
和unless
的示例场景:
import Control.Monad
main :: IO ()
main = do
input <- getLine
when (input == "hello") $ putStrLn "Hello, World!"
import Control.Monad.State
data AppState = AppState { count :: Int }
incrementCount :: State AppState ()
incrementCount = do
state <- get
when (count state < 10) $ modify (\s -> s { count = count s + 1 })
在上述示例中,when
函数根据条件执行相应的操作,从而实现了特定的逻辑。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云