Home > Mobile >  How to import ‘System.IO.Strict’? (HASKELL)
How to import ‘System.IO.Strict’? (HASKELL)

Time:11-17

I am trying to open a file and move the first line last, like so:

-- Moves the first line in a file to the end of the file (first line becomes last line)
flyttLn :: FilePath -> IO ()
flyttLn fn = do
    fh <- openFile fn ReadMode
    content <- hGetContents fh
    --putStrLn content 
    let
        (l1:rest) = lines content
        newContent = unlines (rest  [l1])
    hClose fh
    fh2 <- openFile fn WriteMode
    hPutStr fh2 newContent
    hClose fh2

Which gives me an error because of lazy-evaluation. So based of this question, I first tried to print the contents of the file, and then re-write them. Which works, except I don't want to print the whole file in the terminal. So I tried to import System.IO.Strict like so

import qualified System.IO.Strict as SIO

But VS Code gives me an error saying

Could not find module ‘System.IO.Strict’
It is not a module in the current program, or in any known package.not found

I have tried to find similar problems, but I only found this question, and it didn't help me solve my problem here.

How can I properly, open a file and edit its content, without having to print the whole file in the terminal? How do I import System.IO.Strict correctly?

CodePudding user response:

The module System.IO.Strict is defined in the strict package (I found this using hoogle).

I would recommend making a cabal or stack package yourself and adding strict to the dependencies. For cabal I would recommend the official getting started guide. For stack you can check out the official guide.


Edit: the second part of this answer was not true, you get the same lazy IO problems because the readFile does not finish before the writeFile.

CodePudding user response:

I don't have to import System.IO.Strict with this:

flyttLn :: FilePath -> IO ()
flyttLn file = 
    do 
        fh <- openFile file ReadMode
        content <- hGetContents fh
        let 
            (l1:rest) = lines content
            newContent = unlines (rest  [l1])
        (fn2, fh2) <- openTempFile "." "temp"
        hPutStr fh2 newContent
        hClose fh
        hClose fh2
        removeFile file
        renameFile fn2 file
  • Related