Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Sunday, November 23, 2014

Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog


Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog
def foldLeft[B](z: B)(f: (B, A) => B): B
Firstly, foldLeft is a curried function (So is foldRight). If you don’t know about currying, that’s ok; this function just takes its two parameters (z and f) in two sets of parentheses instead of one. Currying isn’t the important part anyway.
The first parameter, z, is of type B, which is to say it can be different from the list contents type. The second parameter, f, is a function that takes a B and an A (a list item) as parameters, and it returns a value of type B. So the purpose of function f is to take a value of type B, use a list item to modify that value and return it.
The foldLeft function goes through the whole List, from head to tail, and passes each value to f. For the first list item, that first parameter, z, is used as the first parameter to f. For the second list item, the result of the first call to f is used as the B type parameter.
list.foldLeft(List[Int]())((b,a) => a :: b)

Read full article from Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog

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