Tweed

Tweed is a small pure-Ruby library for implementing monads.

Examples

require 'tweed'

The Maybe Monad

Implementing the Maybe monad:

class Maybe < Tweed::Monad
  define_monad do
    construct { |value, success| @value, @success = value, success }
    unit { |value| self.new(value, true) }
    bind { |&block| @success ? block.call(@value) : self }
    zero { self.new(nil, false) }
  end
end

Using the Maybe monad to implement safe division:

module SafeDivision
  def /(other)
    self.bind do |x|
      other.bind do |y|
        y.zero? ? self.class.zero : self.class[x / y]
      end
    end
  end
end

And then using the SafeDivision module:

class X < Maybe
  include SafeDivision
end

success = X[1] / X[2.0] # => X[0.5]
failure = X[1] / X[0]   # => X.zero

This will not result in a zero division error.