Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make this code functional?

i have written a simple script for transforming the c-style identifier names (for example, invoice_number) to java-style ones (like, invoiceNumber).

val files = Vector("file1", "file2")
for (file <- files) {
  val in = io.Source.fromFile(file).mkString
  var out = ""
  var i = 0
  while (i < in.length) {
    val c = in(i)
    if (c == '_') {
      out += in(i + 1).toUpper
      i += 2
    } else {
      out += c
      i += 1
    }
  }
  val writer = new PrintWriter(file + "1")
  writer.write(out)
  writer.flush()
  writer.close()
}

i would like to know how i can make this code functional. i can't think of any higher order function to replace the "increment i by 2 if <some-condition> else increment by 1" logic. thanks.

like image 364
pablo Avatar asked Dec 01 '22 07:12

pablo


1 Answers

Ok, here is my way to do it.

val in = "identifier" :: "invoice_number" :: "some_other_stuff" :: Nil
val out = in map(identifier => {
  val words = identifier.split("_")
  val tail = words.tail.map(_.capitalize)
  (words.head /: tail)(_ + _)
})

println(in)
println(out)

Think it's in reasonable functional style. Interesting how scala gurus will solve this problem :)

like image 51
4e6 Avatar answered Dec 14 '22 08:12

4e6