<!–-markdown-–>

# Tweed

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

[monads]: http://en.wikipedia.org/wiki/Monad_%28functional_programming%29

## Examples

require 'tweed'

### The Maybe Monad

Implementing [the Maybe monad][]:

[the maybe monad]: http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#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.