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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With