Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 19 additions & 30 deletions exercises/practice/pig-latin/.approaches/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,45 +12,34 @@ At the time of writing only four rules need to be handled, but if they have simi
## Approach: `map()` with recursion and `mkString()`

```scala
object PigLatin {
private val vowels = Set('a', 'e', 'i', 'o', 'u')
private val vowels_y = Set('a', 'e', 'i', 'o', 'u', 'y')
private val specials = Set("xr", "yt")
import scala.annotation.tailrec

object PigLatin:

def translate(phrase: String): String = {
private val vowels = Set('a', 'e', 'i', 'o', 'u')
private val vowelsY = Set('a', 'e', 'i', 'o', 'u', 'y')
private val specials = Set("xr", "yt")

def translate(phrase: String): String =
phrase
.split(" ")
.map(word =>
if (vowels.contains(word.head) || specials.contains(word.slice(0, 2)))
word + "ay"
.map: word =>
if vowels.contains(word.head) || specials.contains(word.slice(0, 2)) then word + "ay"
else findVowel(word, 1)
)
.mkString(" ")
}

@scala.annotation.tailrec
private def findVowel(word: String, pos: Int): String = {
word.charAt(pos) match {
case ltr if vowels_y.contains(ltr) => {
val posFix = if (word.slice(pos - 1, pos + 1) == "qu") pos + 1 else pos
word.slice(posFix, word.length()) + word.slice(0, posFix) + "ay"
}
case _ => findVowel(word, pos + 1)
}
}
}

@tailrec
private def findVowel(word: String, pos: Int): String =
word.charAt(pos) match
case ltr if vowelsY.contains(ltr) =>
val posFix = if word.slice(pos - 1, pos + 1) == "qu" then pos + 1 else pos
word.slice(posFix, word.length) + word.slice(0, posFix) + "ay"
case _ => findVowel(word, pos + 1)
```

For more information, check the [`map()` with recursion and `mkString()` approach][approach-map-recursion-mkstring].

[map]: https://www.scala-lang.org/api/2.13.3/scala/Array.html#map[B](f:A=%3EB)(implicitct:scala.reflect.ClassTag[B]):Array[B]
[match]: https://docs.scala-lang.org/tour/pattern-matching.html
[map]: https://www.scala-lang.org/api/current/scala/collection/ArrayOps.html
[recursion]: https://www.geeksforgeeks.org/recursion-in-scala/
[tailrec-annotation]: https://www.scala-lang.org/api/2.12.1/scala/annotation/tailrec.html
[tail-opt]: https://www.baeldung.com/scala/tail-recursion
[pattern-matching]: https://docs.scala-lang.org/tour/pattern-matching.html
[pattern-guard]: https://alvinalexander.com/scala/how-to-use-if-then-expressions-guards-in-case-statements-scala/
[ternary]: https://alvinalexander.com/scala/scala-ternary-operator-syntax/
[mkstring]: https://www.scala-lang.org/api/2.13.3/scala/Array.html#mkString(sep:String):String
[mkstring]: https://www.scala-lang.org/api/current/scala/collection/IterableOnceOps.html
[approach-map-recursion-mkstring]: https://exercism.org/tracks/scala/exercises/pig-latin/approaches/map-recursion-mkstring
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
# `map()` with recursion and `mkString()`

```scala
object PigLatin {
private val vowels = Set('a', 'e', 'i', 'o', 'u')
private val vowels_y = Set('a', 'e', 'i', 'o', 'u', 'y')
private val specials = Set("xr", "yt")
import scala.annotation.tailrec

object PigLatin:

def translate(phrase: String): String = {
private val vowels = Set('a', 'e', 'i', 'o', 'u')
private val vowelsY = Set('a', 'e', 'i', 'o', 'u', 'y')
private val specials = Set("xr", "yt")

def translate(phrase: String): String =
phrase
.split(" ")
.map(word =>
if (vowels.contains(word.head) || specials.contains(word.slice(0, 2)))
word + "ay"
.map: word =>
if vowels.contains(word.head) || specials.contains(word.slice(0, 2)) then word + "ay"
else findVowel(word, 1)
)
.mkString(" ")
}

@scala.annotation.tailrec
private def findVowel(word: String, pos: Int): String = {
word.charAt(pos) match {
case ltr if vowels_y.contains(ltr) => {
val posFix = if (word.slice(pos - 1, pos + 1) == "qu") pos + 1 else pos
word.slice(posFix, word.length()) + word.slice(0, posFix) + "ay"
}
case _ => findVowel(word, pos + 1)
}
}
}

@tailrec
private def findVowel(word: String, pos: Int): String =
word.charAt(pos) match
case ltr if vowelsY.contains(ltr) =>
val posFix = if word.slice(pos - 1, pos + 1) == "qu" then pos + 1 else pos
word.slice(posFix, word.length) + word.slice(0, posFix) + "ay"
case _ => findVowel(word, pos + 1)
```

This approach starts by defining some [Set][set]s to to hold the vowels, vowels with `y`, and the special groups of letters.
This approach starts by defining some [Set][set]s to hold the vowels, the vowels with `y`, and the special groups of letters.

The input phrase is split on a space character and the word or words are chained to the [`map()`][map] method.
Each word is passed to the [lambda][lambda] which consists of an `if/else` expression.
Each word is passed to the [lambda][lambda] which consists of an `if`/`then`/`else` expression.
The lambda is the last argument of `map()`, so it can follow a [colon instead of being wrapped in braces][fewer-braces].
If the `Set` of vowels includes the first character of the word (also called the [`head`][head]), or if a [`slice()`][slice]
of the first two characters is one of the special groups of letters, then `map()` outputs the word appended with `ay`.

Expand All @@ -48,33 +44,31 @@ A tail call is a particular form of [recursion][recursion] where the last call i
In other words, if the last call in `recurMe()` is `recurMe(arg1, arg2) + 1`, the `+ 1` makes the recursion non-tail recursive.

If the last call in `recurMe()` is `recurMe(arg1, arg2, acc + 1)`, then the recursion is a tail call, because only the method is being called
with no other operation being peformed on it.
with no other operation being performed on it.

A [`match`][match] expression is used to perform [pattern matching][pattern-matching] on the result of passing the position
to the [`charAt()`][charat] method.

A [pattern guard][pattern-guard] is used to check if the character is a vowel (`y` is considered a vowel at this point.)
If so, the positon is adjusted if the previous character and the current character are `qu`, otherwise it stays the same.
If so, the position is adjusted if the previous character and the current character are `qu`, otherwise it stays the same.
The `match` returns a `slice()` from the position until the end of the word, to which is concatenated a `slice()` from the
beginning of the word up to but not including the character at the position, to which is concatenated `ay`.
beginning of the word up to but not including the character at the position, to which is concatenated `ay`.

If the character is not a vowel, then `findVowel()` calls itself, passing in the same word and adding `1` to the position.

After all of the words have been mapped, they are reassembled into a string by the [`mkString()`][mkstring] method.

[set]: https://www.scala-lang.org/api/2.13.3/scala/collection/immutable/Set.html
[head]: https://www.scala-lang.org/api/2.13.3/scala/collection/StringOps.html#head:Char
[slice]: https://www.scala-lang.org/api/2.13.3/scala/collection/StringOps.html#slice(from:Int,until:Int):String
[map]: https://www.scala-lang.org/api/2.13.3/scala/Array.html#map[B](f:A=%3EB)(implicitct:scala.reflect.ClassTag[B]):Array[B]
[set]: https://www.scala-lang.org/api/current/scala/collection/immutable/Set.html
[head]: https://www.scala-lang.org/api/current/scala/collection/StringOps.html
[slice]: https://www.scala-lang.org/api/current/scala/collection/StringOps.html
[map]: https://www.scala-lang.org/api/current/scala/collection/ArrayOps.html
[lambda]: https://www.geeksforgeeks.org/lambda-expression-in-scala/
[underscore]: https://www.baeldung.com/scala/underscore
[match]: https://docs.scala-lang.org/tour/pattern-matching.html
[fewer-braces]: https://docs.scala-lang.org/scala3/reference/other-new-features/indentation.html#optional-braces-for-method-arguments
[match]: https://docs.scala-lang.org/scala3/book/control-structures.html#match-expressions
[recursion]: https://www.geeksforgeeks.org/recursion-in-scala/
[tailrec-annotation]: https://www.scala-lang.org/api/2.12.1/scala/annotation/tailrec.html
[tailrec-annotation]: https://www.scala-lang.org/api/current/scala/annotation/tailrec.html
[tail-opt]: https://www.baeldung.com/scala/tail-recursion
[pattern-matching]: https://docs.scala-lang.org/tour/pattern-matching.html
[charat]: https://www.scala-lang.org/api/2.12.8/scala/collection/immutable/StringOps.html#charAt(x$1:Int):Char
[pattern-guard]: https://alvinalexander.com/scala/how-to-use-if-then-expressions-guards-in-case-statements-scala/
[ternary]: https://alvinalexander.com/scala/scala-ternary-operator-syntax/
[mkstring]: https://www.scala-lang.org/api/2.13.3/scala/Array.html#mkString(sep:String):String
[approach-map-recursion-mkstring]: https://exercism.org/tracks/scala/exercises/pig-latin/approaches/map-recursion-mkstring
[charat]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html
[pattern-guard]: https://docs.scala-lang.org/scala3/book/control-structures.html#using-if-guards-in-case-clauses
[mkstring]: https://www.scala-lang.org/api/current/scala/collection/IterableOnceOps.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
phrase
.split(" ")
.map(word =>
if (vowels.contains(word.head) || specials.contains(word.slice(0, 2)))
word + "ay"
.map: word =>
if vowels.contains(word.head) || specials.contains(word.slice(0, 2)) then word + "ay"
else findVowel(word, 1)
)
.mkString(" "
.mkString(" ")
21 changes: 10 additions & 11 deletions exercises/practice/pig-latin/.meta/Example.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
object PigLatin {
private val vowelRegex = "(^|\\s+)(a|e|i|o|u|yt|xr)(\\w+)".r
private val consonantRegex = "(^|\\s+)(?<consonant>ch|qu|thr|th|sch|yt|rh|\\wqu|\\w)(?<rest>\\w+)".r
private val vowelReplacement = "$1$2$3ay"
private val consonantReplacement = "$1$3$2ay"
object PigLatin:

def translate(phrase: String): String =
vowelRegex.findFirstIn(phrase) match {
case Some(x) => vowelRegex.replaceAllIn(phrase, vowelReplacement)
case None => consonantRegex.replaceAllIn(phrase, consonantReplacement)
}
}
private val VowelSound = "(?:[aeiou]|xr|yt).*".r
private val ConsonantSound = "([^aeiouy]*qu|[^aeiou][^aeiouy]*)(.*)".r

def translate(phrase: String): String = phrase.split(" ").map(translateWord).mkString(" ")

private def translateWord(word: String): String = word match
case VowelSound() => word + "ay"
case ConsonantSound(cluster, rest) => rest + cluster + "ay"
case _ => word
3 changes: 2 additions & 1 deletion exercises/practice/pig-latin/.meta/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"contributors": [
"ErikSchierboom",
"ppartarr",
"rajeshpg"
"rajeshpg",
"rabestro"
],
"files": {
"solution": [
Expand Down
10 changes: 10 additions & 0 deletions exercises/practice/pig-latin/.meta/template.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{%- import "macros.j2" as macros -%}
{{ macros.header("PigLatin") }}
{% for case in cases %}

{{ macros.test_open(case) }}
{% if not loop.first %}
pending
{% endif %}
{{ macros.assert_be("PigLatin.translate(" ~ (case.input.phrase | scala) ~ ")", case.expected | scala) }}
{% endfor %}
15 changes: 15 additions & 0 deletions exercises/practice/pig-latin/.meta/tests.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ description = "first letter and ay are moved to the end of words that start with
[bce94a7a-a94e-4e2b-80f4-b2bb02e40f71]
description = "first letter and ay are moved to the end of words that start with consonants -> word beginning with q without a following u"

[e59dbbe8-ccee-4619-a8e9-ce017489bfc0]
description = "first letter and ay are moved to the end of words that start with consonants -> word beginning with consonant and vowel containing qu"

[c01e049a-e3e2-451c-bf8e-e2abb7e438b8]
description = "some letter clusters are treated like a single consonant -> word beginning with ch"

Expand Down Expand Up @@ -74,3 +77,15 @@ description = "position of y in a word determines if it is a consonant or a vowe

[44616581-5ce3-4a81-82d0-40c7ab13d2cf]
description = "phrases are translated -> a whole phrase"
include = false
comment = "Reimplemented by 44616581-5ce3-4a81-82d0-40c7ab13d2d0"

[44616581-5ce3-4a81-82d0-40c7ab13d2d0]
description = "phrases are translated -> a whole phrase"
include = false
comment = "Reimplemented by 44616581-5ce3-4a81-82d0-40c7ab13d2d1"
reimplements = "44616581-5ce3-4a81-82d0-40c7ab13d2cf"

[44616581-5ce3-4a81-82d0-40c7ab13d2d1]
description = "phrases are translated -> a whole phrase"
reimplements = "44616581-5ce3-4a81-82d0-40c7ab13d2d0"
2 changes: 2 additions & 0 deletions exercises/practice/pig-latin/src/main/scala/PigLatin.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
object PigLatin:
def translate(phrase: String): String = ???
Loading
Loading