Skip to content

Instantly share code, notes, and snippets.

@jsanz
Created October 30, 2012 22:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jsanz/3983407 to your computer and use it in GitHub Desktop.
Save jsanz/3983407 to your computer and use it in GitHub Desktop.
Scala collections: mapping letters example
package week6
import scala.io.Source
object collections {
/* read a file of words */
val in = Source.fromURL("http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/linuxwords.txt")
/* create a list and filter all words where *all* their characters are not letters (like dashes) */
val words = in.getLines.toList filter (word => word forall (chr => chr.isLetter))
/* define the map of numbers to letters */
val nmem = Map( '2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL", '6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ")
/* invert the map the get a map of letters to digits */
val charCode: Map[Char, Char] = for ((digit, str) <- nmem; ltr <- str) yield ltr -> digit
/* define a function that returns the numbers of a given word */
def wordCode(word: String): String = word.toUpperCase map charCode
/* group all words of our long list with the same number */
val wordsForNum: Map[String, Seq[String]] = words groupBy wordCode withDefaultValue Seq()
/* function that receives a number and finds the words that match it */
def encode(number: String): Set[List[String]] =
if (number.isEmpty) Set(List())
else {
for {
split <- 1 to number.length // iterate over the number
word <- wordsForNum(number take split) // get the word before the spilt
rest <- encode(number drop split) //get the words after the split
} yield word :: rest // join the results
}.toSet // pass a set to the for
/* better print of the results */
def translate(number: String): Set[String] = encode(number) map (_ mkString " ")
/* test the translate and print results*/
translate("7225247386") foreach println //> sack air fun
//| pack ah re to
//| pack bird to
//| Scala ire to
//| Scala is fun
//| rack ah re to
//| pack air fun
//| sack bird to
//| rack bird to
//| sack ah re to
//| rack air fun
}
@valtih1978
Copy link

valtih1978 commented May 30, 2017

It is not nmem, it is mnem which stands for "mnemonics". Your variables are named improperly.

@fjbanezares
Copy link

do you really care?

@fjbanezares
Copy link

gracias Jorge por tenerlo todo tan ordenadito :p

@shivankurkapoor
Copy link

@PatrickEifler
Copy link

Thanks a lot for posting the updated link 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment