A Heroku-like name generator in Scala

I use a lot temporary directories at work; unfortunately I end up with headaches when I’ve spent my whole day browsing these directories which looks like SHA-1 hash keys. I love developing for the Heroku platform in my spare time, and I think one of the coolest thing is their application random naming feature. If you don’t name your application at creation time, then Heroku will randomly pick a name for you. It looks like an haiku; an evoking image of the natural world. That name is unique, human-friendly, and definitely cool!

A few examples:

  • delicate-spectrum-1819
  • late-equinox-7634
  • snowy-sea-8407
  • strong-drake-4157
  • silent-cloud-2920
  • divine-dream-2340
  • fluffy-mountain-2939
  • green-cedar-3646
  • winter-night-9260
  • powerful-equinox-8694

The following Scala lines return a Heroku-like name like the ones above; feel free to use this anywhere you need random and human-friendly tokens.

import scala.util.Random.nextInt

// full dictionaries at https://github.com/bmarcot/haiku
val adjs = List("autumn", "hidden", "bitter", "misty", "silent",
  "reckless", "daunting", "short", "rising", "strong", "timber", "tumbling",
  "silver", "dusty", "celestial", "cosmic", "crescent", "double", "far",
  "terrestrial", "huge", "deep", "epic", "titanic", "mighty", "powerful")

val nouns = List("waterfall", "river", "breeze", "moon", "rain",
  "wind", "sea", "morning", "snow", "lake", "sunset", "pine", "shadow", "leaf",
  "sequoia", "cedar", "wrath", "blessing", "spirit", "nova", "storm", "burst",
  "giant", "elemental", "throne", "game", "weed", "stone", "apogee", "bang")

def getRandElt[A](xs: List[A]): A = xs.apply(nextInt(xs.size))

def getRandNumber(ra: Range): String = {
  (ra.head + nextInt(ra.end - ra.head)).toString
}

def haiku: String = {
  val xs = getRandNumber(1000 to 9999) :: List(nouns, adjs).map(getRandElt)
  xs.reverse.mkString("-")
}

print(haiku)

You may want to check out the GitHub project instead. It comes with a richer dictionary with more adjectives and words. There are also useful functions to check the uniqueness of words into the dictionary, should you want to add your own ones.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s