Commits

Anonymous committed 2f8fbf1

Work on the Maybe monad -- implement Nothing as a monadic zero.

Comments (0)

Files changed (1)

lib/tweed/monads/maybe.rb

         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
       
-      def self.fail
-        self.new(nil, false)
+      def inspect
+        repr = @success ? "Just #{@value.inspect}" : "Nothing"
+        "#{self.class.inspect} :: #{repr}"
       end
       
       # An example of safe division implemented over the Maybe monad.
       module SafeDivision
         def /(other)
-          self.bind do |val1|
-            other.bind do |val2|
-              val2.zero? ? self.class.fail : self.class.return(val1 / val2)
+          self.bind do |x|
+            other.bind do |y|
+              y.zero? ? self.class.fail : self[x / y]
             end
           end
         end # def /
       end # module SafeDivision
-      
     end # class Maybe
   end # module Monads
 end # module Tweed