此Scala代码的功能样式

时间:2011-08-14 16:07:18

标签: scala coding-style

我的一位朋友正在学习Scala,并编写了这个简单的代码来跟踪文件中最长的一行:

val longest = (filename:String) => {
  val is = new FileInputStream(filename)
  val buf = new Array[Byte](1024)
  var longest=0 //keep track of the longest line
  var lastPos=0
  var read=0
  try {
    read = is.read(buf)
    while (read > 0) {
      for (i<-0 until read) {
        if (buf(i) == '\n') {
          val size=i-lastPos-1
          lastPos=i
          if (size>longest) {
            longest=size
          }
        }
      }
      lastPos-=buf.length
      read=is.read(buf)
    }
  } finally {
    is.close()
  }
  longest
}

我也是Scala的新手,但我很确定此代码中有flatMaps和其他函数的空间。

有人可以发布此功能版吗?

3 个答案:

答案 0 :(得分:24)

另一种实施方式:

def longest(filename: String) =
  Source.fromFile(filename).getLines.map(_.size).max

简要说明:

  • getLines返回文件中行的迭代器;
  • map(_.size),相当于map(line => line.size),返回行长度的新迭代器
  • max返回最大的行长。

答案 1 :(得分:13)

val longest = (filename: String) =>
  io.Source.fromFile(filename).getLines.maxBy(_.length).length

答案 2 :(得分:5)

是的,这段代码非常迫切。在Scala中,粗略的等价物是(!):

def longest(fileName: String) = 
  Source.fromFile(fileName).getLines().max(Ordering.fromLessThan[String](_.size < _.size)).size

猜猜提供一些解释不会有什么坏处:

def longest(fileName: String) = Source.
    fromFile(fileName).     //file contents abstraction
    getLines().     //iterator over lines
    max(        //find the max element in iterated elements
        Ordering.fromLessThan[String](_.size < _.size)  //however, use custom comparator by line size
    ).size  //max() will return the line, we want the line length

当然,Scala中的TMTOWTDI