pig latin
background
The final section of the eighth chapter of the rust book ends with some suggested exercises. The second of which is to write a program that:
Convert strings to Pig Latin. The first consonant of each word is moved to the end of the word and ay is added, so first becomes irst-fay. Words that start with a vowel have hay added to the end instead (apple becomes apple-hay). Keep in mind the details about UTF-8 encoding!
solution
At the time, I thought the simplest approach would be to find Rust’s set-like
structure to store and test for vowels. It seemed like a HashSet was that
structure:
use std::collections::HashSet;
fn main() {
let w1 = String::from("apple");
let w2 = String::from("first");
println!("{}", to_pig_latin(&w1));
println!("{}", to_pig_latin(&w2));
}
fn to_pig_latin(word: &String) -> String {
let vowels = HashSet::from(['a', 'e', 'i', 'o', 'u']);
let first = word.chars().next().unwrap();
if vowels.contains(&first) {
return format!("{word}hay")
} else {
let rest = &word[1..];
return format!("{rest}{first}ay")
}
}
applehay
irstfay
Looking back, we could have made vowels a global constant.
There’s also a bug when word is an empty string; we unwrap irresponsibly without
handling when there is no next.
Something like this could have been better in retrospect:
let first = match word.chars().next() {
Some(character) => character,
None => return String::new()
};