Tuesday, November 18, 2014

Introduction to the Scala Shell


Introduction to the Scala Shell
This chapter will teach you the basics of using the Scala shell and introduce you to functional programming with collections. If you're already comfortable with Scala or plan on using the Python shell for the interactive Spark sections of this mini course, skip ahead to the next section. This exercise is based on a great tutorial, First Steps to Scala . However, reading through that whole tutorial and trying the examples at the console may take considerable time, so we will provide a basic introduction to the Scala shell here. Do as much as you feel you need (in particular you might want to skip the final "bonus" question). Launch the Scala console by typing: /root/scala-2.10.3/bin/scala Declare a list of integers as a variable called "myNumbers". scala> val myNumbers = List(1, 2, 5, 4, 7, 3) myNumbers: List[Int] = List(1, 2, 5, 4, 7, 3) Declare a function, cube , that computes the cube (third power) of an Int. See steps 2-4 of First Steps to Scala. scala> def cube(a: Int):

def factorial(n:Int):Int = if (n==0) 1 else n * factorial(n-1)
  1. import scala.io.Source
  2. val lines = Source.fromFile("/root/spark/README.md").getLines.toArray
val emptyCounts = Map[String,Int]().withDefaultValue(0)
val words = lines.flatMap(line => line.split(" "))
val counts = words.foldLeft(emptyCounts)({(currentCounts: Map[String,Int], word: String) => currentCounts.updated(word, currentCounts(word) + 1)})
Read full article from Introduction to the Scala Shell

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.