teaching machines

CS 330 Lecture 39 – Dynamic Typing, Duck Typing, Multiple Inheritance

May 7, 2014 by . Filed under cs330, lectures, spring 2014.

Agenda

Code

sum.rkt

#lang racket

(define (sum l)
  (cond ((number? l) l)
        ((and (list? l) (not (null? l))) (+ (sum (car l)) (sum (cdr l))))
        (else 0)))

duck.rb

#!/usr/bin/env ruby

def double x
  x + x
end

class NoPlus
end

class YesPlus
  def + other
    10.times do 
      puts "\a"
      sleep 1
    end
  end
end

puts double 5
puts double "kwee"
# puts double NoPlus.new 
puts double YesPlus.new

mixin.rb

#!/usr/bin/env ruby

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 NumberNumber
  def initialize i
    @i = i
  end

  def i
    @i
  end

  def <=> other
    @i - other.i
  end

  include Comparable
end

five = NumberNumber.new 5
six = NumberNumber.new 6
puts five < six

Haiku

I’ve got two parents
But only one grandparent
That makes me special