我有以下方法
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
val lines = paragraph.split("\n")
return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
}
其中l.split(" ")
被调用两次。
如何以函数式编程风格编写更聪明的方法?
PS 1:如果有可能,我对fold
的解决方案感到好奇
PS 2:为了便于阅读,原始版本写为
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
val lines = paragraph.split("\n")
var results = mutableListOf<Pair<Date, String>>()
for (line in lines) {
val content = line.split(" ")
val date: Date = dateFormat.parse(content[0])
val firstName = content[1]
results.add(Pair(date,firstName))
}
return results
}
fold
的方法。val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> =
paragraph.split("\n")
.map {
with(it.split(" ")) { dateFormat.parse(this[0]) to this[1] }
}
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
val lines = paragraph.split("\n")
return lines.fold(listOf<Pair<Date, String>>()) { list, second ->
with (second.split(" ")) {
list + Pair(dateFormat.parse(this[0]), this[1])
}
}
}