teaching machines

CS 330 Lecture 39 – Mixins and Wrap-up

May 10, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

Code

vec3.rb

module Comparable
  def < other
    (self <=> other) < 0
  end

  def > other
    (self <=> other) > 0
  end

  def <= other
    !(self > other)
  end

  def >= other
    !(self < other)
  end

  def == other
    (self <=> other) == 0
  end

  def != other
    !(self == other)
  end

  def between?(lo, hi)
    lo <= self && self < hi
  end
end

class Vector3
  include Comparable

  attr_reader :xyz

  def initialize(*args)
    if args.length == 0
      @xyz = [0, 0, 0]
    else
      @xyz = [args[0], args[1], args[2]]
    end
  end

  def [] i
    @xyz[i]
  end

  def []=(i, value)
    @xyz[i] = value
  end

  def to_s
    xyz.to_s
  end

  def <=> other
    @xyz <=> other.xyz
  end
end

a = Vector3.new
b = Vector3.new(1, 2, 3)
puts a, b
puts a <=> b
puts a < b
puts a > b
puts a == b
puts a != b
puts Vector3.new(1, 1, 1).between?(a, b)

Haiku

What’s the best language?
There’s no good answer to that
Chuck Norris’s fist