我已经写了一小段代码,它处理控制台输入:缩短代码处理IO
main :: IO()
main = do
input <- readLine "> "
loop input
loop :: String -> IO()
loop input = do
case input of
[] -> do
new <- readLine "> "
loop new
"quit" ->
return()
_ -> do
handleCommand input
new <- readLine "> "
loop new
handleCommand :: String -> IO()
handleCommand command = do
case command of
"a" -> putStrLn "it was a"
"b" -> putStrLn "it was b"
_ -> putStrLn "command not found"
readLine :: String -> IO String
readLine prompt = do
putStr prompt
line <- getLine
return line
的代码工作正常,但它看起来丑陋,是多余的。在Scala中我成功把它写短:
object Test extends App {
val reader = Iterator.continually(readLine("> "))
reader takeWhile ("quit" !=) filter (_.nonEmpty) foreach handleCommand
def handleCommand(command: String) = command match {
case "a" => println("it was a")
case "b" => println("it was b")
case _ => println("command not found")
}
}
我试图与IO单子在Haskell使用高阶函数,但我失败了。有人可以给我一个例子如何缩短Haskell代码吗?
另一个问题是,输出的顺序是不同的。在Scala中是正确的:
$ scala Test
> hello
command not found
> a
it was a
> b
it was b
> quit
而在Haskell是不是:
$ ./test
hello
> command not found
a
> it was a
b
> it was b
quit
> %
如何解决这个问题?
顺便说一句,斯卡拉也可以变得更短,使用与你在这里基本相同的布局。 – 2012-02-28 06:08:22
这正是我正在寻找的。非常感谢! – sschaef 2012-02-28 09:22:24