【问题标题】:Haskell: Continue program executionHaskell:继续执行程序
【发布时间】:2015-01-21 13:22:42
【问题描述】:

我对 Haskell 很陌生。我的问题对你来说可能非常基本。我来了-

我正在编写一个程序来使用特定的数学公式创建一系列数字。创建这个系列后,我应该对其执行一些操作,例如从这些数字中找出最大值/最小值。

我可以编写程序,但是在从用户那里获得单个输入后,我的程序会显示输出然后退出。如果我必须等待用户发出更多命令并在命令 END 时退出,我该怎么办?

line <- getLine

我正在使用这个命令来获取一个命令,然后根据命令调用必要的函数。我应该如何进行?

【问题讨论】:

    标签: haskell flow


    【解决方案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
    

    interact :: (String -> String) -> IO () 交互函数将 String->String 类型的函数作为其参数。来自标准输入设备的全部输入作为参数传递给该函数,结果字符串在标准输出设备上输出。

    【讨论】:

      【解决方案2】:

      一个基本的输入循环:

      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 () 退出循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-29
        • 2015-10-31
        • 1970-01-01
        相关资源
        最近更新 更多