teaching machines

CS 330 Lecture 34 – Scala on the JVM, Higher-order Functions, and Parallelism

April 29, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

Intentions

  1. I understand the Uniform Access Principle and its motivation.
  2. I can discover how Scala maps to the JVM.
  3. I can use Scala’s parallel collection routines to accelerate computation.

Uniform Access Principle

Bertrand Meyer said:

All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.

Program This

Write a method getSize accepts a File and the size of this file (if it is a regular file) or the size of its contents (if it is a directory).

Code

Player.scala


class Player(var hitPoints: Int) {
  var isZombie : Boolean = false

  // To get a hook for setting hitPoints:
  //   1. Make a private instance variable:
  //      private var privateHitPoints = hitPoints;
  //   2. Expose a setter with a unique name.
  // def hitPoints_=(newHP: Int): Unit = { 
    // if (isZombie) 
      // hitPonts -= asdfds 
    // else 
      // hitPoints += adfasd 
  // } 
}

object Main {
  def main(args: Array[String]) {
    val player = new Player(100)
    player.hitPoints = 50 + 9000;
  }
}

Player.rb

#!/usr/bin/env ruby

class Player

  def init hit_points
    @hit_points = hit_points
  end

  def hit_points
    @hit_points
  end

  def hit_points= new_hit_points
    @hit_points = new_hit_points
  end

end

BigSys.scala

import java.io.File


object BigSys {
  def main(args: Array[String]) {
    args.foreach(path => {
      printf("%30d %s%n", getSize(new File(path)), path)
    })
  }

  def getSize(file: File): Long = {
    if (!file.isDirectory)
      file.length
    else {
      val contents = file.listFiles
      if (contents != null)
        contents.par.map(file => getSize(file)).sum
      else
        0
    }
      // file.listFiles.map(file => getSize(file)).sum 
  }
}

Haiku

Nerds learn fast, mostly
Part of Scala trips them up
The social functions