haskell 如果在读取之前它不存在则写入文件

haskell write to file it if it does not exists before reading

我正在学习 haskell 并且偶然发现 parse error on input contents' 编译错误。

我想做什么:

我将之前的会话状态存储在一个文件中。我在启动程序之前阅读了这个文件。但是,在程序的第一个 运行 期间,文件可能不存在。在这种情况下,我想首先使用默认值创建文件,然后继续。

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"

此外,我认为与其将 dummyBoard 写入文件,不如使用 dummyBoard 初始化内容。但是我也没有做到。而且我想两者的方式应该相同。

请帮忙。 谢谢。

编辑 解决方案:

else 需要 haskell 中的每个 if

在这个问题之后你会面临的另一个问题是: *** Exception: ashish-temp.txt: openFile: resource busy (file is locked)

使用 import qualified System.IO.Strict as SS.redFile 读取文件。

您的代码库存在一些问题:

  • 您缺少 if 表达式的 else 部分。在 Haskell 中,由于 if 是一个表达式,因此它需要 else 部分,而不是其他语言,其中 if-else 是语句,else 部分不是必需的。
  • dim 到底是什么?你必须定义它。

一个在概念上与您想要做的事情相似的工作程序如下所示:

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"

您的问题的第二部分尚未得到解答。

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.

确实可以,如下:

contents <- if fileExist
    then readFile fileName
    else return $ unlines dummyBoard