'Haskell: Continue program execution

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?



Solution 1:[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.

Solution 2:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 utdemir