A friend of mine is learning Scala and wrote this simple code to keep track of the longest line in a file:
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.
Could someone post a functional version of this?
Scala lets you write code in an object-oriented programming (OOP) style, a functional programming (FP) style, and even in a hybrid style, using both approaches in combination.
Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”.
Scala is functional Scala is also a functional language in the sense that every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functionshigher-order functionsIn mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself a procedure), returns a function as its result.https://en.wikipedia.org › wiki › Higher-order_functionHigher-order function - Wikipedia, it allows functions to be nested, and it supports currying.
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;map(_.size)
, equivalent to map(line => line.size)
, returns a new iterator of the line lengthsmax
returns the greatest line length.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With