拿这个简单的代码:
var line = "";
do {
println("Please enter a non-empty line: ")
line = readLine()
} while (line.isEmpty())
println("You entered a non-empty line: " + line)
它绝对不是特别优雅,尤其是不幸的范围界定line
——然而,我认为它很容易阅读。
现在尝试将其直接转换为scalaz效果,我想出了:
def nonEmptyLine: IO[String] = for {
_ <- putStrLn("Please enter a non-empty line:")
line <- readLn
r <- if (line.isEmpty()) nonEmptyLine else IO(line)
} yield r
(for {
line <- nonEmptyLine
_ <- putStrLn("You entered a non-empty line: " + line)
} yield ()).unsafePerformIO
这让我觉得我错过了一些东西,因为这根本不像是一种改进?我缺少一些更高阶的控制流吗?