9

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

4

1 回答 1

11

它的一般形式是组合choice,它具有以下类型:

choice :: Stream s m t => [ParsecT s u m a] -> ParsecT s u m a

基本上,你给它一个解析器列表,它会按顺序尝试它们,直到一个成功。choice是使用 实现(<|>)的,因此与该方法相同。

在您的情况下,要匹配关键字列表但不匹配其他解析器,您可以映射sstring列表String然后choice在其上使用。

另一方面,mapM string它会做一些完全不同的事情——它会期望所有的解析器都按顺序成功。

于 2013-02-22T14:23:07.750 回答