module Monads::Monad

Public Class Methods

included(base) click to toggle source
# File lib/ruby-monads/monad.rb, line 3
def self.included(base)
  base.class_eval do
    private_class_method :new
  end
end
new(value) click to toggle source
# File lib/ruby-monads/monad.rb, line 9
def initialize(value)
  @value = value
end

Public Instance Methods

fmap(&block) click to toggle source
fmap

(a -> b) -> M a -> M b

# File lib/ruby-monads/monad.rb, line 14
def fmap(&block)
  bind do |value|
    self.class.unit(block.call(value))
  end
end
join() click to toggle source
join

M (M a) -> M a

# File lib/ruby-monads/monad.rb, line 21
def join
  value = @value.is_a?(monad_type) ? @value.unwrap(nil) : @value
  monad_type.unit(value)
end
method_missing(method, *args, &block) click to toggle source
# File lib/ruby-monads/monad.rb, line 26
def method_missing(method, *args, &block)
  fmap do |value|
    value.public_send(method, *args, &block)
  end
end

Private Instance Methods

ensure_monadic_result(&block) click to toggle source
# File lib/ruby-monads/monad.rb, line 34
def ensure_monadic_result(&block)
  proc do
    block.call(@value).tap do |result|
      unless result.is_a?(monad_type)
        raise TypeError, "block must return #{monad_type.name}"
      end
    end
  end
end