Sean Kearon
Sean Kearon

Reputation: 11427

Parse using a list of strings in FParsec

I am checking for reserved words using something like this:

let astr s = attempt (pstringCI s)
let reservedWord = astr "text" <|> astr "date" // etc.

Is it possible to create a parser performs the same check but which takes an array of the reserved words as a parameter? Something like:

newReservedWordParser "something" ["text"; "date"; ...]

Upvotes: 1

Views: 180

Answers (2)

Tyrrrz
Tyrrrz

Reputation: 2611

Why not use choice? It takes a seq as parameter.

You can use it like so:

let reservedWords = [
    "word1"
    "word2"
]

let parseReservedWord = reservedWords |> List.map pstringCI |> choice

I'm doing something similar in my project here

Upvotes: 2

Sean Kearon
Sean Kearon

Reputation: 11427

Having stumbled across the answer from @bytebuster here, this can be done like so (not sure I need this any longer though!):

let reservedWord (reservedWords: string list) = 
    (many1 letter |>> System.String.Concat) >>= 
    fun x -> 
        if List.contains x reservedWords then preturn x 
        else fail "not a reserved word"

LINQPad share here.

FParsec documentation about >>= is here.

Upvotes: 0

Related Questions