dyoder / functor

Implements pattern-based method dispatch for Ruby, inspired by Topher Cyll's multi.

This URL has Read+Write access

functor / metrics / many_args.rb
100644 71 lines (64 sloc) 1.537 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require "#{here = File.dirname(__FILE__)}/helpers"
 
class A
  include Functor::Method
  functor( :foo, 1, 2, 3, 4, 5, 6, 7 ) { |*x| "ints" }
  functor( :foo, :a, :b, :c, :d, :e, :f, :g ) { |*x| "symbols" }
  functor( :foo, *%w{ a b c d e f g } ) { |*x| "strings" }
  functor( :foo, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 ) { |*x| "floats" }
  functor( :foo, *Array.new(7, "one") ) { |*x| "ones" }
end
 
class Native
  def foo(*args)
    case args
    when [1, 2, 3, 4, 5, 6, 7]
      "ints"
    when [:a, :b, :c, :d, :e, :f, :g]
      "symbols"
    when %w{ a b c d e f g }
      "strings"
    when [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
      "floats"
    when Array.new(7, "one")
      "ones"
    else
      raise ArgumentError
    end
  end
end
 
class ManyArgs < Steve
end
 
ManyArgs.new "native method" do
  before do
    @args = [
      [1, 2, 3, 4, 5, 6, 7],
      [:a, :b, :c, :d, :e, :f, :g],
      %w{ a b c d e f g },
      [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],
      Array.new(7, "one")
      ]
    @n = Native.new
  end
  measure do
    400.times do
      @args.each { |args| @n.foo *args }
    end
  end
end
 
 
ManyArgs.new "functor method" do
  before do
    @args = [
      [1, 2, 3, 4, 5, 6, 7],
      [:a, :b, :c, :d, :e, :f, :g],
      %w{ a b c d e f g },
      [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],
      Array.new(7, "one")
      ]
    @a = A.new
  end
  measure do
    400.times do
      @args.each { |args| @a.foo *args }
    end
  end
end
 
ManyArgs.compare_instances( 4, 64)