Instructions on how to run it.
a.Copy the below mentioned code into a file named SourceInput .
b. Run > scalac SourceInput .scala
c. Run > scala SourceInput
import scala.io._
object SourceInput {
def main(args: Array[String]) {
println("Enter some numbers and press ctrl-D (Unix/Mac) ctrl-C (Windows)")
val input = Source.fromInputStream(System.in)
val lines = input.getLines.toSeq
println("Sum "+lines.mkString)
}
def toInt(in: String): Option[Int] =
try {
Some(Integer.parseInt(in.trim))
} catch {
case e: NumberFormatException => None
}
def sum(in: Seq[String]) = {
val ints = in.flatMap(s => toInt(s))
ints.foldLeft(0)((a, b) => a + b)
}
}
Observations:
a. Methods are defined as def.
b. Vals are scala's way of defining Immutable objects.
c. Source is a scala class for fetching Inputstream from System.in
d. s => toInt(s) is scala's way of handling lamda expression. See Post on why scala for more on lamda calculus.
e. Option[Int] is a elegant way of handling the way values are returned.Option is a container that one or zero things.If it holds zero elements ,its None which is a signleton,which means that one instance of None. If the option holds one elements, it's some(element).
f. Unlike java importing many classes one uses _(underscore) instead of asterisk(*)

No comments:
Post a Comment