我已經寫了一小段代碼,它處理控制檯輸入:縮短代碼處理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