Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 474
OscarRyz Avatar asked Aug 14 '11 16:08

OscarRyz


People also ask

What is functional program design in Scala?

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.

What is functional style of programming?

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”.

How is Scala functional?

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.


1 Answers

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 lengths
  • max returns the greatest line length.
like image 184
Ben James Avatar answered Sep 27 '22 23:09

Ben James