整理它的一个简单的第一次尝试就是删除前导部分Console.
尾随的;
和明确的:String
type - 所有这些都是不必要的 - 添加一些缩进并导入 io.Source:
import io.Source
println(
Source.fromFile("names.txt").getLines.mkString.split(",").map{
x => x.slice(1, x.length -1)
}.sortBy {x => x}.zipWithIndex.map{
t =>{ (t._2 +1)*(t._1.map{_.toChar - "A"(0).toChar + 1}.sum)}
}.sum
)
下一步是稍微清理一下,在映射元组列表时使用模式匹配,identity
代替x=>x
. toChar
对于字符来说也是不必要的,可以使用单引号来表示字符文字。
import io.Source
println(
Source.fromFile("names.txt").getLines.mkString.split(",").map {
x => x.slice(1, x.length -1)
}.sortBy(identity).zipWithIndex.map {
case (v, idx) =>{ (idx+1)*(v.map{_ - 'A' + 1}.sum)}
}.sum
)
更多的更改也有助于使代码的意图更加清晰:
import io.Source
println(
Source.fromFile("names.txt").getLines.mkString.split(",")
.map { _.stripPrefix("\"").stripSuffix("\"") }
.sortBy(identity)
.map { _.map{_ - 'A' + 1}.sum }
.zipWithIndex
.map { case (v, idx) => (idx+1) * v }
.sum
)
下一步,为了使其更加“功能化”,是将其分解为“功能”(偷偷摸摸的,是吧?)。理想情况下,每个函数都有一个清楚表达其用途的名称,并且该名称很短(目标是单个表达式,因此不需要大括号):
import io.Source
def unquote(s:String) = s.stripPrefix("\"").stripSuffix("\"")
def wordsFrom(fname:String) =
Source.fromFile(fname).getLines.mkString.split(",").map(unquote)
def letterPos(c:Char) = c - 'A' + 1
println(
wordsFrom("names.txt")
.sortBy(identity)
.map { _.map(letterPos).sum }
.zipWithIndex
.map { case (v, idx) => (idx+1) * v }
.sum
)
wordsFrom
是一个明显的单行代码,但我将其拆分以便在 stackOverflow 上更轻松地格式化