Class: Monadt::Monad

Inherits:
Object
  • Object
show all
Defined in:
lib/monadt.rb,
lib/monadt/monad.rb

Class Method Summary collapse

Class Method Details

.async(&blk) ⇒ Object



24
25
26
# File 'lib/monadt.rb', line 24

def async(&blk)
  do_m(Async, &blk)
end

.async_either(&blk) ⇒ Object



28
29
30
# File 'lib/monadt.rb', line 28

def async_either(&blk)
  do_m(AsyncEither, &blk)
end

.do_m(klass, &blk) ⇒ Object



37
38
39
# File 'lib/monadt/monad.rb', line 37

def do_m(klass, &blk)
  do_m_fiber(klass, &blk)
end

.do_m_enum(klass, &blk) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/monadt/monad.rb', line 60

def do_m_enum(klass, &blk)
  e = Enumerator.new do |y|
    m_obj = Internal::MonadObjEnum.new klass, y
    blk.call(m_obj)
  end
  do_m_recur_enum(klass, e)
end

.do_m_fiber(klass, &blk) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/monadt/monad.rb', line 41

def do_m_fiber(klass, &blk)
  f = Fiber.new do |y|
    m_obj = Internal::MonadObjFiber.new klass
    blk.call(m_obj)
  end
  do_m_recur_fiber(klass, f, nil)
end

.do_m_recur_enum(klass, e) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/monadt/monad.rb', line 68

def do_m_recur_enum(klass, e)
  begin
    ma = e.next
  rescue StopIteration => ex
    return ex.result
  end
  klass.bind(ma) do |a|
    e.feed a
    do_m_recur_enum(klass, e)
  end
end

.do_m_recur_fiber(klass, f, ma, *args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/monadt/monad.rb', line 49

def do_m_recur_fiber(klass, f, ma, *args)
  if f.alive?
    ma = f.resume(*args)
    klass.bind(ma) do |a|
      do_m_recur_fiber(klass, f, ma, a)
    end
  else
    ma
  end
end

.either(&blk) ⇒ Object



20
21
22
# File 'lib/monadt.rb', line 20

def either(&blk)
  do_m(Either, &blk)
end

.maybe(&blk) ⇒ Object



12
13
14
# File 'lib/monadt.rb', line 12

def maybe(&blk)
  do_m(Maybe, &blk)
end

.present(&blk) ⇒ Object



16
17
18
# File 'lib/monadt.rb', line 16

def present(&blk)
  do_m(Present, &blk)
end

.reader(&blk) ⇒ Object



41
42
43
# File 'lib/monadt.rb', line 41

def reader(&blk)
  do_m(Reader, &blk)
end

.reader_state_choice(&blk) ⇒ Object



49
50
51
# File 'lib/monadt.rb', line 49

def reader_state_choice(&blk)
  do_m(ReaderStateEither, &blk)
end

.run_reader(env, &blk) ⇒ Object



45
46
47
# File 'lib/monadt.rb', line 45

def run_reader(env, &blk)
  reader(&blk).(env)
end

.run_reader_state_choice(env, initial_state, &blk) ⇒ Object



53
54
55
# File 'lib/monadt.rb', line 53

def run_reader_state_choice(env, initial_state, &blk)
  reader_state_choice(&blk).(env, initial_state).first
end

.run_state(initial_state, &blk) ⇒ Object



36
37
38
39
# File 'lib/monadt.rb', line 36

def run_state(initial_state, &blk)
  prc = state(&blk)
  prc.(initial_state).first
end

.state(&blk) ⇒ Object



32
33
34
# File 'lib/monadt.rb', line 32

def state(&blk)
  do_m(State, &blk)
end