Skip to content

Instantly share code, notes, and snippets.

@sam
Last active December 19, 2015 15:49
Show Gist options
  • Save sam/5979128 to your computer and use it in GitHub Desktop.
Save sam/5979128 to your computer and use it in GitHub Desktop.
Top Ten Words in a String.
object Main extends App {
val wordCount = "(\\w+)".r
.findAllIn(_:String)
.toSeq
.groupBy(_.toLowerCase)
.mapValues(_.size)
.toSeq
.sortBy(_._2)
.reverse
val topTen = wordCount andThen(_.take(10).map(_._1))
println(topTen("My name is Sam, sam is a super great name yo! SAM! Sam. sam"))
}
@sam
Copy link
Author

sam commented Jul 11, 2013

Here's a tweaked version optimizing out the reverse:

object Main extends App {

  val wordCount = "(\\w+)".r
    .findAllIn(_:String)
    .toSeq
    .groupBy(_.toLowerCase)
    .mapValues(_.size)
    .toSeq
    .sortBy(-_._2)

  val topTen = wordCount andThen(_.take(10).map(_._1))

  println(topTen("My name is Sam, sam is a super great name yo! SAM! Sam. sam"))
}

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