Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Parsing Expression Grammar to Turn Buffalo into Fish
/*
* Use this at http://pegjs.majda.cz/online
*
* Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
* - becomes -
* Fishy fish fishy fish fish fish fishy fish
*
* Also, the grammar is recursive, so it could also generate ALL THE FISH.
*/
start
= np:nounphrase " " vp:verbphrase "." { var s = np + " " + vp + "."; return s.charAt(0).toUpperCase() + s.slice(1); }
nounphrase
= pn:propernoun " " n:noun " " rc:relativeclause { return pn + " " + n + " " + rc; }
/ pn:propernoun " " n:noun { return pn + " " + n; }
verbphrase
= v:verb " " np:nounphrase { return v + " " + np; }
relativeclause
= np:nounphrase " " v:verb { return np + " " + v; }
propernoun = "Buffalo" { return "fishy" }
noun = "buffalo" { return "fish"; }
verb = "buffalo" { return "fish"; }
@brendanberg

This comment has been minimized.

Copy link
Owner Author

@brendanberg brendanberg commented Nov 15, 2012

Input: "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo Buffalo buffalo Buffalo buffalo Buffalo buffalo buffalo buffalo buffalo."
Output: "Fishy fish fishy fish fish fish fishy fish fishy fish fishy fish fishy fish fish fish fish."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.