gpt4 book ai didi

haskell - 了解 Parsec 中的 SourceName

转载 作者:行者123 更新时间:2023-12-03 23:55:36 27 4
gpt4 key购买 nike

我对 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com