Haskell - loop over user input

后端 未结 4 984
半阙折子戏
半阙折子戏 2021-02-13 21:40

I have a program in haskell that has to read arbitrary lines of input from the user and when the user is finished the accumulated input has to be sent to a function.

In

4条回答
  •  星月不相逢
    2021-02-13 22:17

    The Haskell equivalent to iteration is recursion. You would also need to work in the IO monad, if you have to read lines of input. The general picture is:

    import Control.Monad
    
    main = do
      line <- getLine
      unless (line == "q") $ do
        -- process line
        main
    

    If you just want to accumulate all read lines in content, you don't have to do that. Just use getContents which will retrieve (lazily) all user input. Just stop when you see the 'q'. In quite idiomatic Haskell, all reading could be done in a single line of code:

    main = mapM_ process . takeWhile (/= "q") . lines =<< getContents
      where process line = do -- whatever you like, e.g.
                              putStrLn line
    

    If you read the first line of code from right to left, it says:

    1. get everything that the user will provide as input (never fear, this is lazy);

    2. split it in lines as it comes;

    3. only take lines as long as they're not equal to "q", stop when you see such a line;

    4. and call process for each line.

    If you didn't figure it out already, you need to read carefully a Haskell tutorial!

提交回复
热议问题