Haskell Parsec,将oneOf调整为[String] [英] Haskell Parsec, adapting oneOf to [String]
问题描述
我正在通过48小时的教程写下自己的计划。
符号::解析器Char
symbol = oneOf!#$%& | * + - /:< ; =>?@ ^ _〜
这对符号很有用,但如果我有关键字列表? (即struct,int)
是否可以修改为列表?
关键字::解析器字符串
关键字= oneOf [struct ,int,.. etc]
或者我应该导入Text.Parsec.Char并尝试mapM字符串在关键字列表中吗?
我试图标记化,只是想知道哪些最佳实践来自沿着这条路走下去的其他人。
文档声明使用如下所示:
divOrMod = stringdiv
< |>字符串mod
http://hackage.haskell.org/packages/archive/parsec/3.0.0/doc/html/Text-Parsec-Char .html
这个的一般形式是 选择
combinator ,其类型如下:
choice :: Stream smt => [ParsecT s u m a] - > ParsecT suma
基本上,您给它一个解析器列表,然后按顺序尝试它们直到一个成功。 choice 是使用
(< |>)
实现的,因此它与该方法相同。
在你的情况下,为了匹配一个关键字列表,但没有其他解析器,你可以将 string
映射到 String
s然后使用 choice
就可以了。
另一方面, mapM string
会做一些完全不同的事情 - 它会希望解析器的所有顺序执行。
I'm going through the Write yourself a scheme in 48 hours tutorial.
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
This is great for symbols, but what if I have a list of keywords? (i.e. struct, int)
can oneOf be adapted to lists? This is ideally what I want, depicted below.
keywords :: Parser String
keywords = oneOf ["struct","int",..etc]
Or should I import Text.Parsec.Char and try to mapM string over the list of keywords?
I'm attempting to tokenize and just wanted to know what best practices were from others who have gone down this road.
The docs say to use something like this:
divOrMod = string "div"
<|> string "mod"
http://hackage.haskell.org/packages/archive/parsec/3.0.0/doc/html/Text-Parsec-Char.html
The general form of this is the choice
combinator, which has the following type:
choice :: Stream s m t => [ParsecT s u m a] -> ParsecT s u m a
Basically, you give it a list of parsers, and it tries them in order until one succeeds. choice
is implemented using (<|>)
, so it's the same as that approach.
In your case, to match a list of keywords but no other parsers, you can just map string
over a list of String
s and then use choice
on that.
On the other hand, mapM string
would do something entirely different--it would expect all of the parsers to succeed in order.
这篇关于Haskell Parsec,将oneOf调整为[String]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!