Skip to content

Instantly share code, notes, and snippets.

@p1xelHer0
Created December 1, 2024 19:56
Show Gist options
  • Save p1xelHer0/98633ed78e74485c6827d08493884a8d to your computer and use it in GitHub Desktop.
Save p1xelHer0/98633ed78e74485c6827d08493884a8d to your computer and use it in GitHub Desktop.
OCaml Scanf parsing
(* I overuse these two badboys *)
let parse fmt map line = try Some (Scanf.sscanf line fmt map) with _ -> None
let rec try_parse parsers line =
match parsers with
| [] -> failwith ("could not parse: " ^ line)
| parse :: parsers -> (
match parse line with
| None -> try_parse parsers line
| Some result -> result
)
(* example from AoC 2021 day 14 *)
(* see https://adventofcode.com/2021/day/14 *)
type growth = {
opening : Char.t;
closing : Char.t;
value : Char.t;
}
(* we want to parse these *)
type instruction =
| Reaction of growth
| Polymer of string
(* data looks like this *)
(* NNCB *)
(* CH -> B *)
(* HH -> N *)
(* CB -> H *)
(* try to parse a [Polymer], then a [Reaction] *)
(* just match these printf style strings with the function and tadaaaa *)
let parsers =
[
parse "%s" (fun s -> Polymer s);
parse "%c%c -> %c" (fun opening closing value ->
Reaction { opening; closing; value }
);
]
let instructions = List.map ~f:(try_parse parsers) lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment