Posts Tagged ‘latin’

Programming Praxis – Pig Latin

June 2, 2009

Today‚Äôs Programming Praxis problem is about Pig Latin. Our target is 11 lines (the size of the provided solution). Et’s-lay egin-bay.

We convert to pig latin by putting all consonants before the first vowel (or a w if there are none) at the end, followed by “ay”.

toPigLatin :: String -> String
toPigLatin w = let (h, t) = break (flip elem "aeiouAEIOU") w
               in t ++ "-" ++ (if null h then "w" else h) ++ "ay"

And to go back we do the opposite. Put all the consonants in the postfix before the rest of the word. In this implementation I use the reverse of the word so I can easily remove the “ay” by pattern matching. Alternatively you can use something like takeWhile (/= ‘a’) h.

fromPigLatin :: String -> String
fromPigLatin w = let ('y':'a':h, '-':t) = break (== '-') $ reverse w
                 in reverse $ t ++ if h == "w" then "" else h

Since the provided solution has a function that both encodes and decodes, let’s make one too.

pigLatin :: String -> String
pigLatin w = if elem '-' w then fromPigLatin w else toPigLatin w

And of course some tests to see if it works:

main :: IO ()
main = do
    print . map pigLatin $ words "art eagle start door spray prays wart"
    print . map pigLatin $ words
        "art-way eagle-way art-stay oor-day ay-spray ays-pray art-way"

And we’re done. 5 lines of code. Iece-pay of-way ake-cay.