gpt4 book ai didi

haskell - 学习 haskell `parsec` : trying to rewrite `words` function as a basic exercise

转载 作者:行者123 更新时间:2023-12-02 01:43:38 25 4
gpt4 key购买 nike

这是一个非常基本的问题,老实说,我觉得写它有点傻。

TL;DR: 我如何编写一个函数来使用 parsec 库来模仿 words 函数的行为 数据列表?预期行为的示例:

wordsReplica "I love lamp" = ["I","love","lamp"]

我刚刚阅读了 Real World Haskell 中 Parsec 一章的前几页,这对理解什么是最低限度的解析函数(一个不仅仅返回参数的函数)非常有帮助或什么都不返回)。 (RWH 的介绍性示例展示了如何解析多行 CSV 文件...)

因此,我认为使用 parsec 重写 words 是一个有用的基本练习...结果证明不是那么基本(对我来说)...

以下是我的尝试;不幸的是,无论我给它什么,它都会产生一个“意外的输入结束”错误(在运行时)。我试过阅读 haskell.org 上 parsec 库中简单函数的描述/定义,但它们并没有那么说明性,至少对于以前从未做过任何类型的解析的人来说,包括其他语言。

testParser :: String -> Either ParseError [[String]]
testParser input = parse dcParser "(unknown)" input
where
wordsReplica = endBy
(sepBy
(many (noneOf " "))
(char ' '))
(char ' ')

(请原谅 lisp-y、非无意义的演示 - 当我学习一个新函数时,如果我使符号/结构非常明确,它会帮助我。)

更新:
这是朝着正确方向迈出的一步(但仍然不完全正确,因为它不计算数字):

λ: let wordsReplica = sepBy (many letter) (char ' ')
λ: parse wordsReplica "i love lamp 867 5309"
Right ["i","love","lamp",""]

更新 2:

似乎这个函数完成了工作,但我不确定它是多么地道:

λ: let wordsReplica = sepBy (many (satisfy(not . isSpace))) (char ' ')
wordsReplica :: Stream s m Char => ParsecT s u m [[Char]]

λ: parse wordsReplica "" "867 5309 i love lamp %all% !(nonblanks are $$captured$$"

Right ["867","5309","i","love","lamp","%all%","!(nonblanks","are","$$captured$$"]
it :: Either ParseError [[Char]]

最佳答案

Update 2:

Seems like this function gets the job done, though am not sure how idiomatic it is.

没问题,但它没有按您的预期工作:

> words "Hello      world"["Hello","world"]> parse wordsReplica "" "Hello      world"Right ["Hello","","","","","","world"]

Not quite what you want. After all, a word should consist of at least one character. But if you change many to many1, you will notice another error:

> parse wordsReplicaMany1 "" "Hello      world"Left (line 1, column 7):unexpected " "

That's because your separating parser isn't greedy enough. Instead of parsing a single space, parse as many as you can:

nonSpace      = satisfy $ not . isSpace
wordsReplica' = many1 nonSpace `sepBy` spaces

关于haskell - 学习 haskell `parsec` : trying to rewrite `words` function as a basic exercise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987402/

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