[英]Functional style for this Scala code
我的一個朋友正在學習 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 和其他功能。
有人可以發布這個的功能版本嗎?
另一種實現:
def longest(filename: String) =
Source.fromFile(filename).getLines.map(_.size).max
簡要說明:
getLines
返回文件中行的迭代器;map(_.size)
,等價於map(line => line.size)
,返回一個新的行長迭代器max
返回最大的行長度。val longest = (filename: String) =>
io.Source.fromFile(filename).getLines.maxBy(_.length).length
是的,這段代碼非常必要。 在 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.