Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I was wondering if someone had any suggestions on how to make this code snippet more elegant.

val names = Buffer[String]()
var name: String = null
do {
  val input = readLine("Name: ")
  if (names contains input) {
    println("Name was taken already. Try again.")
  } else {
    name = input
  }
} while (name == null)
share|improve this question
add comment

1 Answer

up vote 11 down vote accepted

Currently the code is not very elegant (or at least not very functional) because it contains mutable variables and a while loop. So let's get rid of those.

In functional languages we can usually achieve the most elegant solutions if we're working with sequences (e.g. lists or streams) as input. If we had the input as a sequence of strings in this case, we could simply write this to get the first name not in the list of names:

inputNames.find( !names.contains(_) )

So how do we get the input into a stream? We can use Stream.continually to create an infinite, lazy stream of input:

def askForName() = readLine("Name: ")

def askForNameAgain() = {
    println("Name was taken already. Try again.")
    askForName()
}

def inputNames = Stream.cons( askForName(), Stream.continually(askForNameAgain()))

val name = inputNames.find( !names.contains(_) )

Note that this way name will be a Option[String]. If the user closes the input stream before entering a valid name, name will be None. Otherwise it will be Some(theName). If you want to ignore the possibility that the user may close the stream, you can simply add a call to Option.get.

share|improve this answer
    
Excellent, thank you sepp2k. Very nice solution. So much to learn from scala.. :) –  Dale Wijnand Sep 3 '11 at 7:23
    
Excellent answer. I was vaguely feeling a lazy stream was the answer, but I was unable to express it, even less in the elegant way you did. –  PhiLho Sep 5 '11 at 9:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.