I wrote a simplified pig latin translator in APL and I would like some feedback on it, as I am not sure my implementation is neat enough.
The simplified pig latin translation follows the following rules, where only 'aeiouAEIOU' are considered vowels:
- one-letter words have
'way'appended to them; e.g.'I'becomes'Iway' - 2 or more letter words starting with a vowel have
'ay'appended to them; e.g.'awesome'becomes'awesomeay' - 2 or more letter words starting with a consonant have the consonants in front of the first vowel moved to the back, and then
'ay'is appended; e.g.'cool'becomes'oolcay'
The problem statement (problem 3 of the second easy problem set) specified that input might be a scalar (i.e. a single character) or a (possibly empty) character vector.
This is the code I wrote:
PigLatin ← { ⍝ Monadic function expecting character scalar or character vector and returning character vector. ⍝ Translates an English sentence into Pig lating. ⍝ e.g. 'I always run fast' becomes 'Iway alwaysay unray astfay'. vowels ← 'aeiouAEIOU' words ← ' ' (≠⊆⊢) ,⍵ ⍝ Rotate all words until a vowel is at the front. rotated ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}¨ words ⍝ Append a 'w' to words of length 1. suffixed ← (,∘'w')¨@(1∘=≢¨) rotated ⍝ Append 'ay ' to all words, join and drop last ' '. ¯1↓∊ (,∘'ay ')¨ suffixed } Questions
The basic idea is that I split the input sentence into words, apply the rules to each word and then join them together; this seems sensible, right? This feels like a very standard algorithm but I don't know if APL is suitable for another type of approach.
Following the idea outlined above, my first version had this final line
∊ {⍺' '⍵}/ (,∘'ay')¨ suffixedinstead of the current¯1↓ ∊(,∘'ay ')¨ suffixed; but this meant my code didn't work for empty inputs''because it tried running{⍺' '⍵}/on an empty vector and raised a DOMAIN ERROR. My workaround for this was appending'ay 'to every word, instead of just'ay'and then dropping the final extra' 'with¯1↓;- Is this a good way of handling the edge case
''? - Would it be better if I had a dfn guard for the
''case? - Would you handle it in a different way?
- Is this a good way of handling the edge case
Is
≠⊆⊢an idiom in APL to split the right vector on the left arguments? It even shows in the tooltip for the Partition⊆glyph.Any further comments, suggestions, etc that don't necessarily address my questions are also welcome.