Haskell Parsec, adapting oneOf to [String]

做~自己de王妃 提交于 2019-12-10 03:34:38

问题


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


回答1:


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 Strings 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.



来源:https://stackoverflow.com/questions/15026081/haskell-parsec-adapting-oneof-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!