Haskell: read the file line by line

I recently made Waterloo CCC , and I feel that Haskell is the perfect language to answer these questions. I'm still learning this. However, I'm struggling a bit with input.

Here is what I use:

import IO
import System.Environment
import System.FilePath


main = do
    name <- getProgName
    args <- getArgs
    input <- readFile $
        if not (null args)
            then head args
            else dropExtension name ++ ".in"
    let (k:code:_) = lines input
    putStrLn $ decode (read k) code

As you can see, I am reading from a given path to the command line or from j1.in, for example, if this program is called j1.hsand compiled into j1.

I'm only interested in the first two lines of the file, so I used pattern matching to get these lines and bind them to kand codein this example. And then I read kas an integer and passed it and a line of code to my function decode, which I output.

, readFile , . , , , Haskell , - , . ?

, - , , .

+5
4

readFile :

readFile . , , getContents.

, , ( , , , ). readFile, , / Haskell .

Lazy I/O - I/O- (, webservers), , -.

+8

, readFile . , :

import Control.Monad (replicateM)
import System.IO

readLines n f = withFile f ReadMode $ replicateM n . hGetLine

-- in main
    (k:code:_) <- readLines 2 filename

, .

, , .

+6

readFile , , . , , , .

+3
Haskell's I / O is usually not lazy. However, the function readFileis lazy. Others said the same thing. What I have not seen, indicates that the file that you opened will not be closed until the program ends or the garbage collector is started. This means that the file descriptor of the OS can remain open longer than necessary. In your program, this probably doesn't matter much. But in a more complex project, this may be.
+2
source

All Articles