简体   繁体   English

此 Scala 代码的功能样式

[英]Functional style for this Scala code

A friend of mine is learning Scala and wrote this simple code to keep track of the longest line in a file:我的一个朋友正在学习 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
}

I'm new to Scala too, but I'm pretty sure there's a lot of room for flatMaps and other functions in this code.我也是 Scala 的新手,但我很确定这段代码中有很多空间用于 flatMaps 和其他功能。

Could someone post a functional version of this?有人可以发布这个的功能版本吗?

An alternative implementation:另一种实现:

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

Brief explanation:简要说明:

  • getLines returns an iterator of the lines in the file; getLines返回文件中行的迭代器;
  • map(_.size) , equivalent to map(line => line.size) , returns a new iterator of the line lengths map(_.size) ,等价于map(line => line.size) ,返回一个新的行长迭代器
  • max returns the greatest line length. max返回最大的行长度。
val longest = (filename: String) =>
  io.Source.fromFile(filename).getLines.maxBy(_.length).length

Yes, this code is painfully imperative.是的,这段代码非常必要。 In Scala the rough equivalent would be (:):在 Scala 中,粗略的等价物是 (:):

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

Guess it wouldn't hurt to provide some explanation:猜猜提供一些解释不会有什么坏处:

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

Of course TMTOWTDI in Scala.当然是Scala中的 TMTOWTDI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM