【发布时间】:2026-01-04 23:20:10
【问题描述】:
我在 Haskell 中编写一个函数作为编译器的一部分来打开一个文件,从中读取一组文件名并将它们连接成一个字符串。该代码在 ghci 中运行良好,但在使用以下内容编译时失败:
fact.fn: openFile: 不存在(没有这样的文件或目录)
我完全确定 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))
【问题讨论】:
-
你是在同一个目录下运行的吗?可执行文件的位置无关紧要:它采用
pwd并将文件名添加到其中。 -
除了 Willem 的评论 - 如果您在 Windows 上:如果在 PowerShell 上
pwd被预定义为Get-Location的别名,它返回当前位置。在 CMDpwd不可用时,要获取当前目录运行cd(不带任何参数)。 -
我在 Ubuntu 上,我确实在同一个目录中运行。我什至复制到新目录以检查权限。