Haskell - loop over user input

后端 未结 4 974
半阙折子戏
半阙折子戏 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 22:18

    Using pipes-4.0, which is coming out this weekend:

    import Pipes
    import qualified Pipes.Prelude as P
    
    f :: [String] -> IO ()
    f = ??
    
    main = do
        contents <- P.toListM (P.stdinLn >-> P.takeWhile (/= "q"))
        f contents
    

    That loads all the lines into memory. However, you can also process each line as it is being generated, too:

    f :: String -> IO ()
    
    main = runEffect $
        for (P.stdinLn >-> P.takeWhile (/= "q")) $ \str -> do
            lift (f str)
    

    That will stream the input and never load more than one line into memory.

提交回复
热议问题