Friday, September 11, 2015

Pig Latin

Pig Latin is a somewhat ridiculous language game which modifies words in such a funny way that is hard to figure out if you don't know how it works but easy if you do. Using Factor, we will build a converter from English to Pig Latin words.

There are two basic rules we should implement:

  1. For words that begin with consonant sounds, the initial consonant or consonant cluster is moved to the end of the word, and "ay" is added to the end.
{ "igpay" } [ "pig" pig-latin ] unit-test
{ "ananabay" } [ "banana" pig-latin ] unit-test
{ "ashtray" } [ "trash" pig-latin ] unit-test
{ "appyhay" } [ "happy" pig-latin ] unit-test
{ "uckday" } [ "duck" pig-latin ] unit-test
{ "oveglay" } [ "glove" pig-latin ] unit-test
  1. For words that begin with a vowel sounds or silent letter, add "way" to the end.
{ "eggway" } [ "egg" pig-latin ] unit-test
{ "inboxway" } [ "inbox" pig-latin ] unit-test
{ "eightway" } [ "eight" pig-latin ] unit-test

We can implement our two basic rules:

: pig-latin ( str -- str' )
    dup [ "aeiou" member? ] find drop [
        "way" append
    ] [
        cut swap "ay" 3append
    ] if-zero ;

We could improve this by:

  • better handling of words that start with capital vowels or are all consonants
  • reverse the rules to convert Pig Latin back to English
  • variations such as adding "yay" (or "i") instead of "way"
  • different rules like adding "ag" before each vowel ("pagig lagatagin")
  • support language games in other languages

Anyway, this is available on my GitHub.

No comments:

Post a Comment