Wie kann ich das folgende Stück Code (die toText
-Methode) mit einem höheren Ebene Methoden wie map
verkürzen, takeWhile
, filter
, etc .:Scala - Stück Code mit höherer Ebene Methoden Verkürzung
/** Returns the text that is produced by this keypad from the given multi-tap input.
* For instance, the input `"33 3338881330000"` produces `"HIYAH!"`. The given string
* is assumed to consist of digits and spaces only.
*/
def toText(keysPressed: String): String = {
val pieces = keysPressed.split(" ")
var result = "" // gatherer
for (currentPiece <- pieces) { // most-recent holder
var remaining = currentPiece // gatherer
while (remaining.nonEmpty) {
val copyCount = countInitialCopies(remaining) // temporary
result += charFor(remaining(0), copyCount)
remaining = remaining.drop(copyCount)
}
}
result
}
wo:
/** Returns the character produced by pressing the given number key (from '0' to '9')
* the given number of times on this keypad. If a key is pressed more times than there
* are characters assigned to the key, the result "wraps around".
*/
def charFor(keyPressed: Char, timesPressed: Int): Char = {
val charactersForKeys = Vector(" .,!?", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "ÅÄÖ")
val key = charactersForKeys(keyPressed.asDigit)
key((timesPressed-1) % key.length)
}
und:
/** Determines the first letter of the given string, and returns the number of times
* the letter occurs consecutively at the beginning of the string. The given
* string must have at least one character.
*/
def countInitialCopies(str: String): Int = str.takeWhile(_ == str(0)).length
Ich habe versucht, die folgenden zu tun, aber es ging nicht so weit:
def toText(keysPressed: String): String = keysPressed.split(" ").foldLeft("")(charFor(_(0), countInitialCopies(_)))
Wie unterscheidet sich dieser Code vom Original, außer dass beide Methoden inliniert sind? Ist der Unterschied in einem anderen Ansatz, um Räume zu behandeln? Oder ist es Rekursion statt Schleifen? – SergGr
@SergGr; Ja, Rekursion, unveränderliche Variablen .... Ich sagte, es sei "etwas anders". – jwvh