FParsec tip for handling spaces

I have the following subexpression for parsing quotes, which have the following format

"5.75 @ 5.95"

So I have this parsec expression for parsing it

let pquote x = (sepBy (pfloat) ((spaces .>> (pchar '/' <|>  pchar '@' )>>. spaces))) x

It works great. Unless there is a finite space in my input as the delimiter expression begins to consume content. So I wrapped it around an attempt that works and seems, from what I understand, more or less what it should have been.

let pquote x = (sepBy (pfloat) (attempt (spaces .>> (pchar '/' <|>  pchar '@' )>>. spaces))) x

As I don't know fparsec so well, I wonder if there is a better way to write this. it seems a bit heavy (although still very manageable, of course)

+5
source share
3 answers
let s1 = "5.75         @             5.95              "
let s2 = "5.75/5.95   "
let pquote: Parser<_> =
    pfloat
    .>> spaces .>> skipAnyOf ['@'; '/'] .>> spaces
    .>>. pfloat
    .>> spaces

Notes:

  • spaces spaces , opt - @Daniel;
  • type Parser<'t> = Parser<'t, UserState> - , " "; ;
  • , , , : System.Threading.Thread.CurrentThread.CurrentCulture <- Globalization.CultureInfo.GetCultureInfo "en-US" , @Stephan
  • sepBy, .
  • (, '@' ), skip* p* .

UPD

+6

, , - , float * float:

let ws = spaces
let quantity = pfloat .>> ws
let price = pfloat .>> ws
let quoteSep = pstring "@" .>> ws
let quote = quantity .>> quoteSep .>>. price //`.>> eof` (if final parser)

, . , eof.

+3

Assuming there can be more than two at the input float, and '/' and '@' are delimiters:

let ws = spaces
let str_ws s = pstring s .>> ws
let float_ws = pfloat .>> ws
let pquote = sepBy float_ws (str_ws "/" <|> str_ws "@")

Speaking of handling spaces, this section in the FParsec tutorial is really useful.

+1
source

All Articles