我正在 Haskell 中编写一个函数作为编译器的一部分来打开一个文件,从中读取一组文件名并将它们连接成一个字符串。该代码在 ghci 中运行良好,但在使用以下内容编译时失败:
fact.fn: openFile: does not exist (No such file or directory)
我完全确定fact.fn存在并且它与可执行文件位于同一目录中。
相关代码:
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))
最佳答案
我认为问题在于,在处理如下导入命令时:
import fact.fn
您没有删除文件名开头的空格,因此您的程序实际上是在尝试导入文件“fact.fn”
而不是“fact.fn”
.如果仔细研究错误消息,您可以验证情况是否如此。如果错误是:
*** Exception: fact.fn: openFile: does not exist (No such file or directory)
Exception:
和 fact.fn
之间有两个空格而不是一个空格,则文件名开头会有一个额外的空格。
我完全不知道你是如何在解释器中成功运行它的。
关于Haskell ReadFile 对现有文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52244116/