Haskell ReadFile 对现有文件失败

标签 haskell readfile io-monad

我正在 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/

相关文章:

haskell - 从 Haskell 类型同义词中提取值

debugging - 测试顶级函数内定义的内部函数并与之交互的最佳方法是什么?

javascript - HTML 选择 : how to set drop down text

scala - Scala 标准 API 中的 IO Haskell Monad 等价物是什么?

haskell - 如何在 Ubuntu 上安装最新版本的 Haskell GHC 编译器?

python - 如何使 Read plus (r+) 模式在 python 3 中工作?

c# - 如何从 powerpoint 中读取数据

haskell - 返回 IO 操作的后果是什么?

haskell - 猜我的号码,一元性头痛

Haskell 字节串到 float 组