Class: Distribution

Inherits:
Object
  • Object
show all
Extended by:
PRNG
Includes:
Monad
Defined in:
lib/do_notation/monads/simulations.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from PRNG

next_state

Methods included from Monad

#>>, #bind_const, included

Constructor Details

#initialize(a) ⇒ Distribution

Returns a new instance of Distribution.



47
48
49
# File 'lib/do_notation/monads/simulations.rb', line 47

def initialize(a)
  @a = a
end

Instance Attribute Details

#aObject (readonly)

Returns the value of attribute a.



45
46
47
# File 'lib/do_notation/monads/simulations.rb', line 45

def a
  @a
end

Class Method Details

.rand(n) ⇒ Object



59
60
61
62
# File 'lib/do_notation/monads/simulations.rb', line 59

def self.rand(n) 
  p = 1.0 / n
  new((0...n).map{|i| [i, p]})
end

.unit(x) ⇒ Object



55
56
57
# File 'lib/do_notation/monads/simulations.rb', line 55

def self.unit(x)
  wrap [[x, 1.0]]
end

.wrap(a) ⇒ Object



51
52
53
# File 'lib/do_notation/monads/simulations.rb', line 51

def self.wrap(a)
  new(a)
end

Instance Method Details

#bind(&b) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/do_notation/monads/simulations.rb', line 64

def bind(&b)
  if @a.empty?
    self.class.wrap([])
  else
    x, p = @a[0]
    self.class.wrap(mulp(p, b.call(x)) + self.class.new(@a[1..-1]).bind(&b).a)
  end
end

#playObject



73
74
75
76
77
# File 'lib/do_notation/monads/simulations.rb', line 73

def play
  h = Hash.new{|h, k| h[k] = 0.0}
  @a.each{|x, p| h[x] += p}
  h.to_a.sort_by{|x,| x}
end