Haskell: Continue program execution

做~自己de王妃 提交于 2019-12-14 03:24:18

问题


I am very new to Haskell. My question might be very basic for you. Here I go-

I am writing a program to create a series of numbers using a specific mathematical formula. After creating this series, I am supposed to perform some operation on it like finding the maximum/minimum out of those numbers.

I could write the program but after getting a single input from the user, my program displays the output and then exits. What should I do if I have to wait for more commands from the user and exit on command END?

line <- getLine

I am using this command to get a command and then calling the necessary function according to the command. How should I proceed?


回答1:


A basic input loop:

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

Note how each command handler calls loop again to restart the loop. The "end" handler calls return () to exit the loop.




回答2:


There is Prelude.interact for this:

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 () The interact function takes a function of type String->String as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device.



来源:https://stackoverflow.com/questions/27094540/haskell-continue-program-execution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!