haskell - 了解 Parsec 中的 SourceName

标签 haskell parsec

我对 SourceName 的含义有疑问在 parse函数在 Parsec .似乎我阅读的所有书籍/博客/教程都跳过了它的内容并使用 "stdin" , "(stdin)"或任意字符串,例如 "test parser" .指定为 SourceName 的内容有什么区别吗? ?

我试图阅读 source codeParsec它似乎是用来创建一个位置的。但是为什么它是什么来源很重要(确实是 String)。听起来在大多数情况下我不需要担心它。

提前致谢!

最佳答案

秒差距,SourceNameString用于生成错误消息。在 REPL 中,这不是很重要:

λ> parse expression "<stdin>" ")"
Left "<stdin>" (line 1, column 1):
unexpected ")"
expecting expression

如果我们使用 "foo"而不是 "<stdin>" , 如果看起来像这样:
Left "foo" (line 1, column 1):
unexpected ")"
expecting expression

这在编写以多个文件作为输入的程序时很有用,例如编译器或解释器。例如,在我的解释器中,我有以下功能:
runFile :: FilePath -> IO ()
runFile path = do code  <- readFile path
                  start <- prelude
                  evalString path start code >>= putStrLn

我路过path ——你正在运行的文件的路径——到解析表达式的函数中。这样,错误消息会告诉你哪个文件有解析错误,以及行号。
λ> runFile "/Users/tikhon/tmp/foo.tpl"
Error: "/Users/tikhon/tmp/foo.tpl" (line 1, column 1):
unexpected ')'
expecting expression or end of input!

关于haskell - 了解 Parsec 中的 SourceName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710847/

相关文章:

arrays - 使用数组在 haskell 中解析方案向量

Haskell:秒差距无法打破模式

haskell - 使用 cmdargs 排序参数

haskell - 运算符是什么意思(:>) in a data constructor?

haskell - 在 Haskell 中使用模式匹配时,两种风格的函数定义背后的原因是什么?

haskell - 使用 Parsec 按字符串正确分割

parsing - Haskell 解析 - Parsec 与 Alex

performance - 在 Haskell 的列表列表中有效地找到多个最大值

haskell - 非常简单的代码中的堆栈溢出

haskell - "Unexpected end of input - expecting end of input"(秒差距)