Sign in using Google or Yahoo! id.  

Scala: foldLeft example

 Comments Share:   Twitter   Reddit   HackerNews   Facebook 
import scala.io.Source
import java.util.regex.{Pattern, Matcher}

def stripQuotes(str: String): String = {
    val p:Pattern = Pattern.compile("\"(.*)\"")
    val m: Matcher = p.matcher(str)
    if(m.matches()){
        return m.group(1).trim
    }
    return str.trim
}

val lines = Source.fromFile("my.csv").getLines
val max = lines.foldLeft(0){ (max, line) =>
    val arr = line.split(",")
    val greet = stripQuotes(arr(3))
    val msg = stripQuotes(arr(4))
    val custom = stripQuotes(arr(5))
    val complete = greet + " " + msg + " " + custom
    val len = complete.length
    println(len + ": " + complete)
    if(max < len){
        len
    }
    else{
        max
    }
}

println("\n\nMaximum length of the message: " + max)

Posted on March 02, 2010 08:28 AM by Subhash Chandran
scala
blog comments powered by Disqus