2014-11-23 141 views
0

我對Haskell很新。我的問題對你來說可能是非常基礎的。在這裏我去 - 我正在寫一個程序,使用特定的數學公式來創建一系列數字。在創建這個系列之後,我應該對它進行一些操作,比如從這些數字中找出最大值/最小值。 所以,我可以編寫程序,但在得到用戶的單個輸入後,我的程序顯示輸出並退出。如果我必須等待來自用戶的更多命令並在命令結束時退出,我該怎麼辦?Haskell:繼續執行程序

線< - 函數getline

我使用這個命令來獲取命令,然後根據命令調用所需的功能。我應該如何繼續?

回答

1

基本輸入迴路:

loop = do 
    putStr "Enter a command: " 
    input <- getLine 
    let ws = words input -- split into words 
    case ws of 
    ("end":_)  -> return() 
    ("add":xs:ys:_) -> do let x = read xs :: Int 
           y = read ys 
          print $ x + y 
          loop 
    ... other commands ... 
    _ -> do putStrLn "command not understood"; loop 


main = loop 

注意如何在每個命令處理程序再次調用loop重新啓動循環。 「結束」處理程序調用return()來退出循環。

+0

非常感謝!像魅力一樣工作.. – BW12 2014-11-24 01:38:36

1

Prelude.interact此:

calculate :: String -> String 
calculate input = 
    let ws = words input 
    in case ws of 
     ["add", xs, ys] -> show $ (read xs) + (read ys) 
     _ -> "Invalid command" 

main :: IO() 
main = interact calculate 

相互作用::(字符串 - >字符串) - > 10()的交互作用函數採用類型與字符串>字符串的函數作爲它的參數。來自標準輸入設備的全部輸入將作爲其參數傳遞給此函數,並將生成的字符串輸出到標準輸出設備上。