Class: Distribution

Inherits:
Object
  • Object
show all
Extended by:
Monad, PRNG
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, compose, run

Constructor Details

#initialize(a) ⇒ Distribution

Returns a new instance of Distribution.



49
50
51
# File 'lib/do_notation/monads/simulations.rb', line 49

def initialize(a)
  @a = a
end

Instance Attribute Details

#aObject (readonly)

Returns the value of attribute a.



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

def a
  @a
end

Class Method Details

.bind(distribution, &b) ⇒ Object



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

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

.rand(n) ⇒ Object



61
62
63
64
# File 'lib/do_notation/monads/simulations.rb', line 61

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

.unit(x) ⇒ Object



57
58
59
# File 'lib/do_notation/monads/simulations.rb', line 57

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

.wrap(a) ⇒ Object



53
54
55
# File 'lib/do_notation/monads/simulations.rb', line 53

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

Instance Method Details

#playObject



75
76
77
78
79
# File 'lib/do_notation/monads/simulations.rb', line 75

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