type unit_t = (string * int) list
How would I go about creating an expression to parse a string into this form? Do I need to implement code in a parser.mly
format in order to handle this?
type unit_t = (string * int) list
How would I go about creating an expression to parse a string into this form? Do I need to implement code in a parser.mly
format in order to handle this?
There's no real way to give a detailed answer, since you don't say how the original string is supposed to correspond to your list of pairs.
Based just on the simplicity of your output type, I'd say you could do this without invoking the full machinery of ocamlyacc. I.e., I doubt you need a parser.mly
file. You could use ocamllex, or you could just apply some regular expressions from the Str
module. It depends on what your parsing actually needs to do.
Here's one possibility that uses regular expressions from Str
:
let p s =
let fs = Str.full_split (Str.regexp "[0-9]+") s in
let rec go = function
| [] -> []
| Str.Text s :: Str.Delim i :: rest -> (s, int_of_string i) :: go rest
| Str.Text s :: rest -> (s, 0) :: go rest
| Str.Delim i :: rest -> ("", int_of_string i) :: go rest
in
go fs
You can run it like this:
# #load "str.cma";;
# #use "p.ml";;
val p : string -> (string * int) list = <fun>
# p "123abc456def";;
- : (string * int) list = [("", 123); ("abc", 456); ("def", 0)]
# p "ghi789jkl100";;
- : (string * int) list = [("ghi", 789); ("jkl", 100)]