Reputation: 5301
I am learning haskell and am stumbled upon the parse error on input contents'
compilation error.
What i want to do :
I store my previous session state state in a file. I read this file before starting the program. However, during the first run of program, file may not exist. In this case, i want to first create file first with default value and then proceed ahead.
main :: IO()
main = do
-- Take input
let fileName = "ashish-temp.txt"
let dummyBoard = take 5 $ repeat "-----"
fileExist <- doesFileExist fileName
if False == fileExist
then writeFile fileName $ unlines dummyBoard
-- getting an error on this line
contents <- readFile fileName
-- do processing () :)
-- i want the value in contents
putStrLn "Done"
Also, i think that rather than writing dummyBoard
to the file i can just initialize the contents with dummyBoard
. But i also failed in doing it. And i guess the way should be the same for both.
Please help. Thanks.
Edit Solution:
else
is required for every if
in haskell.
Also another problem that you would face after this problem is :
*** Exception: ashish-temp.txt: openFile: resource busy (file is locked)
use import qualified System.IO.Strict as S
and S.redFile
for reading file.
Upvotes: 4
Views: 3714
Reputation: 18189
You had a second part of the question which hasn't been answered yet.
Also, i think that rather than writing
dummyBoard
to the file i can just initialize the contents withdummyBoard
. But i also failed in doing it. And i guess the way should be the same for both.
Indeed you can, as follows:
contents <- if fileExist
then readFile fileName
else return $ unlines dummyBoard
Upvotes: 1
Reputation: 48734
There are some problem with your codebase:
else
part of your if
expression. In Haskell, since if
is an expression , it would need the else
part as opposed to other languages where the if-else
are statements and the else part is not mandatory.dim
? You have to define it.A working program which shows similar in concept of what you want to do will look like this:
main :: IO()
main = do
let fileName = "somefile.txt"
fileExist <- doesFileExist fileName
if not fileExist
then writeFile fileName "something"
else return ()
contents <- readFile fileName
-- do stuff with contents here
putStrLn "Done"
Upvotes: 6