這裏是你將如何使用裸機遞歸做到這一點:
loop [] = return() -- done with the loop
loop (x:xs) =
do a <- doSomeIO
if ...a...
then return() -- exit the loop
else do -- continuing with the loop
b <- doSomeMoreIO
if ...b...
then return() -- exit the loop
else do -- continuing with the loop
...
loop xs -- perform the next iteration
,然後用調用它:
loop [1..100]
您可以用控制的when
功能有點整理這件事。 Monad:
loop [] = return()
loop (x:xs) =
do a <- doSomeIO
when (not ...a...) $ do
b <- doSomeMoreIO
when (not ...b...) $ do
...
loop xs
Control.Mona中還有unless
d您可能更喜歡使用。
使用@與Orjan約翰森的有用的建議,這裏是一個簡單的例子:
import Control.Monad
loop [] = return()
loop (x:xs) = do
putStrLn $ "x = " ++ show x
a <- getLine
when (a /= "stop") $ do
b <- getLine
when (b /= "stop") $ do
print $ "iteration: " ++ show x ++ ": a = " ++ a ++ " b = " ++ b
loop xs
main = loop [1..3]
上有Hackage提供各種種類的循環了幾包。我見過的最有趣的可能是https://hackage.haskell.org/package/loops – dfeuer
Monad變壓器從來沒有必要 - 只是方便。 –