Last active
December 21, 2015 01:28
-
-
Save whitequark/592981a4842160adffb6 to your computer and use it in GitHub Desktop.
Beautiful tiny FSM encoded with pattern matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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