本文是从“Scala热情交流群(132569382)”的讨论中整理出来。
我想写一个函数:把一个字符串里的b改为*,把结尾的c改为#。一份可行的Scala代码如下:
object Main {
def fix(text: String) = {
val s = text.replace("b", "*")
if (s.endsWith("c")) {
s.stripSuffix("c") + ("#")
} else s
}
def main(args: Array[String]) {
println(fix("abbbbccc")) // -> a***cc#
}
}
可以看出,还是在用java的方式来写,不够函数化,那应该怎么优化呢?
首先,要转变思想,比如使用正则表达式:
def fix(s: String) = s.replace('b', '*').replaceAll("c$", "#")
或者
def fix(s: String) = Some(s.replace('b', '*')).map(s => if(s.endsWith("c")) s.init + "#" else s).get
又或者
def fix(test: String) = text.replace("b", "*") match {
case t if (t.endsWith("c")) => t.stripSuffix("c") + ("#")
case t => t
}
函数式的风格写起来就是很爽,如行云流水一般。从java到scala,不仅仅是语法变了,更重要的是编程的风格,这个转变可不容易。风自由在stackoverflow上问了这个问题,请参见完整版:http://stackoverflow.com/questions/5140465/how-to-optimize-this-simple-function-in-scala