Use FParsec to parse float or int * float

I just started playing with FParsec, and now I'm trying to parse strings in the following format

10*0.5 0.25 0.75 3*0.1 0.9

I want 3 * 0.1, for example, expand to 0.1 0.1 0.1

So far, I have been next

type UserState = unit
type Parser<'t> = Parser<'t, UserState>

let str s : Parser<_> = pstring s

let float_ws : Parser<_> = pfloat .>> spaces

let product = pipe2 pint32 (str "*" >>. float_ws) (fun x y -> List.init x (fun i -> y)) 

The analyzer correctly processes parsers in a format int*floatand expands it to the list of floats. However, I am having problems with a solution that allows me to parse either int*float, or just a float. I would like to do something like

many (product <|> float_ws)

This, of course, will not work, since the types of returned parsers are different. Any ideas on how to make this work? Is it possible to wrap update float_ws so that it returns a list with only one float?

+4
source share
1

float_ws a float list, |>> List.singleton

let float_ws : Parser<_> = pfloat .>> spaces |>> List.singleton

|>> - map, - :

val (|>>): Parser<'a,'u> -> ('a -> 'b) -> Parser<'b,'u>

: http://www.quanttec.com/fparsec/reference/primitives.html#members.:124::62::62:


, product , , , . , <|> , attempt, FParsec .

let combined = many (attempt product <|> float_ws)
+4
source

Source: https://habr.com/ru/post/1627005/


All Articles