Haskell - loop over user input

后端 未结 4 987
半阙折子戏
半阙折子戏 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:40

    It's reasonably simple in Haskell. The trickiest part is that you want to accumulate the sequence of user inputs. In an imperative language you use a loop to do this, whereas in Haskell the canonical way is to use a recursive helper function. It would look something like this:

    getUserLines :: IO String                      -- optional type signature
    getUserLines = go ""
      where go contents = do
        line <- getLine
        if line == "q"
            then return contents
            else go (contents ++ line ++ "\n")     -- add a newline
    

    This is actually a definition of an IO action which returns a String. Since it is an IO action, you access the returned string using the <- syntax rather than the = assignment syntax. If you want a quick overview, I recommend reading The IO Monad For People Who Simply Don't Care.

    You can use this function at the GHCI prompt like this

    >>> str <- getUserLines
    Hello     -- user input
    World     -- user input
    q         -- user input
    >>> putStrLn str
    Hello            -- program output
    World            -- program output
    

提交回复
热议问题