teaching machines

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

Agenda

  • what ?s
  • static vs. dynamic vs. duck
  • multiple inheritance
  • traits/mixins

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *