Skip to content

Instantly share code, notes, and snippets.

@brendanberg
Created November 15, 2012 18:49
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 brendanberg/4080423 to your computer and use it in GitHub Desktop.
Save brendanberg/4080423 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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