Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple FParsec list example

Tags:

f#

fparsec

I'm just getting started with FParsec and can't wrap my head around a simple list parser. Given the input

"{ a;b;c d; }"

I want to get the result ['a';'b';'c';'d']

If I do

let baseChars = ['0'..'9'] @ ['A'..'Z'] @ ['a'..'z'] @ ['_'; '-']
let chars : Parser<_> = anyOf baseChars
let nameChars : Parser<_> = anyOf (baseChars @ ['.'])                

let semiColonList p : Parser<_> = sepBy p (pstring ";")
let pList p : Parser<_> = between (pstring "{") (pstring "}") (semiColonList p)

do  """{
    a;b;c;
    d;
}"""
    |> run (parse {
        let! data = pList (spaces >>. many1Chars nameChars)
        return data
    })
    |> printfn "%A"

I get a failure on the last } as it's trying to match that on the nameChars parser before closing the between parser. This feels like there is a simple solution that I'm missing, especially since if I delete the last semi-colon after d all works as expected. Any help appreciated.

[edit] Thanks to Fyodor Soikin the following works:

    let semiColonList p = many (p .>> (pstring ";" >>. spaces))
    let pList p : Parser<_> = between (pstring "{") (pstring "}") (semiColonList p)
    """{
    a;b;c;
    d;
}"""
    |> run (parse {
        let! data = pList (spaces >>. many1Chars nameChars)
        return data
    })
    |> printfn "%A" 
like image 725
Dylan Avatar asked May 16 '26 20:05

Dylan


1 Answers

sepBy does not admit a trailing separator. A parser like sepBy a b is meant to parse input like a b a b a, but your input is like a b a b a b - there's an extra separator b at the end.

What you want to do instead is to parse multiple expressions that are like a b - that will give you your desired shape of the input.

In order to parse one such expression, use the sequencing operator .>>, and in order to parse multiple such pairs, use many:

semiColonList p = many (p .>> pstring ";")
like image 70
Fyodor Soikin Avatar answered May 19 '26 04:05

Fyodor Soikin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!