The Maybe Monad in Ruby
blog.pretheory.com
blog.pretheory.com
In Rails, there's a file whiny_nil.rb, whose sole job is to report errors about people accessing a nil object when they shouldn't be. Using Maybe with pattern matching, coming from Haskell, makes as much sense as implementing Iterator with first-class functions. It looks weird, coming from Visual Basic, but it makes your code readable and short.
class Maybe:
def __init__(self, obj):
self.o = obj
def __repr__(self):
return repr(self.o)
def __getattr__(self, name):
try:
return Maybe(getattr(self.o,name))
except:
return Maybe(None)
I'm trying to decide whether using it's Pythonic or not.If you wanted this behavior everywhere, you could just include this code
class NilClass
def method_missing(method, *args)
nil
end
end
But I think this would cause more problems than it would solve.