2014-11-23 158 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()的交互作用函数采用类型与字符串>字符串的函数作为它的参数。来自标准输入设备的全部输入将作为其参数传递给此函数,并将生成的字符串输出到标准输出设备上。