Skip to content

Instantly share code, notes, and snippets.

@whitequark
Last active December 21, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whitequark/592981a4842160adffb6 to your computer and use it in GitHub Desktop.
Save whitequark/592981a4842160adffb6 to your computer and use it in GitHub Desktop.
Beautiful tiny FSM encoded with pattern matching
(* OCaml regular expressions are unusual in that they require
parentheses and pipe symbol to be escaped to *gain* special
meaning. swap_escape converts from (and, incidentally, to)
the usual format. *)
let swap_escape input =
let swap_chr (esc, str) chr =
match esc, chr with
(* Go to escape mode. *)
| false, '\\'
-> true, str
(* *Un*escape parens and pipe. *)
| true, '(' | true, '|' | true, ')'
-> false, str ^ (String.of_char chr)
(* Leave other escaped symbols as they are (escaped).
Escape bare parens and pipe. *)
| true, _ | false, '(' | false, '|' | false, ')'
-> false, str ^ "\\" ^ (String.of_char chr)
(* Leave other unescaped symbols as they are (bare). *)
| false, _
-> false, str ^ (String.of_char chr)
in
snd (String.fold_left swap_chr (false, "") input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment