首页 > 解决方案 > Haskell ReadFile fails for existing files

问题描述

I'm writing a function in Haskell as part of a compiler to open a file, read a set of file names from it and concatenate them into a string. The code runs fine in ghci but fails when compiled with the following:

fact.fn: openFile: does not exist (No such file or directory)

I am completely sure fact.fn exists and it's in the same directory as the executable.

Relevant code:

compile [fileName] = do  
             (ilude, contents) <- imports fileName
             let lude = "prelude.fn" : ilude
             prld <- fmap fullPrelude (mapM readFile lude) --seems to fail here, 
--but works fine in the interpreter
             let newPrld = unlines [prld, "\nend"]
             runEvalWith HappyParser.parseExpr fileName contents newPrld


imports :: String -> IO ([String], String)
imports fileName = do 
    contents <- readFile fileName
    let ls = lines contents
    let ifile = filter (isPrefixOf "import") ls {-find import string here-}
    let contentList = filter (\w -> w `notElem` ifile) ls
    let impts = mapMaybe (stripPrefix "import") ifile
    return (impts, (unlines contentList) )


fullPrelude :: [String] -> String
fullPrelude [] = ""
fullPrelude xs = unlines( map (procPrelude) xs)

procPrelude :: String -> String
procPrelude pld = unlines(init(words pld))

标签: haskellreadfileio-monad

解决方案


我认为问题在于,在处理如下导入命令时:

import fact.fn

您没有从文件名的开头剥离空间,因此您的程序实际上是在尝试导入文件" fact.fn"而不是"fact.fn". 如果您仔细研究错误消息,您可以验证是否属于这种情况。如果错误是:

*** Exception:  fact.fn: openFile: does not exist (No such file or directory)

Exception:在and之间有两个空格而不是一个fact.fn,那么文件名的开头会有一个额外的空格。

我完全不知道你是如何在解释器中成功运行它的。


推荐阅读