teaching machines

CS 330 Lecture 35 – Lambdas and Closures Elsewhere

April 28, 2014 by . Filed under cs330, lectures, spring 2014.

Agenda

Code

blocks.rb

#!/usr/bin/env ruby

wilds = [5, 8, 3, 2, 0, 9]

evens = wilds.select do |n|
  n % 2 == 0
end

odds = wilds.select {|n| n % 2 == 1}

puts evens
puts odds

monkey.rb

#!/usr/bin/env ruby

class Array
  def for_each
    for i in 0...length
      yield self[i] 
    end
  end
  
  def map
    xformed = Array.new
    for i in 0...length
      xformed.push(yield self[i])
    end
    xformed
  end
end

ns = [7, 5, 1, 3, 5, "Boo"]
ns.for_each do |n|
  puts n.to_s + '1'
end

names = ['Donatello', 'John', 'Brendon']
xformed = names.map do |name|
  name[0...name.length / 2]
end
puts xformed

BigButton.java

package cs330_egs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class BigButton {
  private static int nClicks = 0;

  public static void main(String[] args) {
    JFrame frame = new JFrame();

    JButton button = new JButton("" + nClicks);
    frame.add(button);

    // button = new JButton("Deal breaker");
    // class ClickListener implements ActionListener {
    // @Override
    // public void actionPerformed(ActionEvent e) {
    // ++nClicks;
    // button.setText("" + nClicks);
    // }
    // }

//    button.addActionListener(new ActionListener() {
//      @Override
//      public void actionPerformed(ActionEvent e) {
//        button.setText("" + nClicks++);
//      }
//    });
    
    button.addActionListener(e -> button.setText("" + nClicks++));

    frame.setSize(1000, 1000);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

TreeDB.java

package cs330_egs;

import java.util.ArrayList;

public class TreeDB {
  public static void main(String[] args) {
    ArrayList<Tree> trees = new ArrayList<>();
    
    trees.add(new Tree("Willow", false, true));
    trees.add(new Tree("Birch", true, true));
    trees.add(new Tree("Cedar", true, false));
    trees.add(new Tree("Baldcypress", true, false));

    String s = trees.stream()
         .filter(t -> t.isConiferous)
         .map(t -> t.name)
         .reduce("", (accumulator, name) -> accumulator + "," + name);
    System.out.println(s);
  }
  
  static class Tree {
    public String name;
    public boolean isConiferous;
    public boolean isDeciduous;
    public boolean isCarnivorous;
    
    public Tree(String name, boolean isConiferous, boolean isDeciduous) {
      this.name = name;
      this.isConiferous = isConiferous;
      this.isDeciduous = isDeciduous;
    }
  }
}

Haiku

Inspired by http://mathwithbaddrawings.com/2014/04/14/anxiety-mathematics-and-words-of-kindness:

“Course N won’t make sense
Till you take course N + 1”
Thus, postrequisites