3 ms·
It's not quite defining a monad, but it's very close. The example given in the article is: data_source.person(id) do |person| person.phone_number =
by DanWaterworth 13y ago
It's not quite defining a monad, but it's very close.
The example given in the article is:
data_source.person(id) do |person|
person.phone_number = phone_number
data_source.update_person person
end
You can abstract this pattern a little by putting it in a function:
def maybe_bind(x, &blk)
if !x.nil?
blk.call(x)
else
nil
end
end
Now consider the type of this function:
nil or X, (X -> nil or Y) -> nil or Y
A monad is any type for which you can define bind and return. They have the Haskell types:
bind :: m a -> (a -> m b) -> m b
return :: a -> m a
"maybe_bind" is very similar to "bind"; just replace "m" with "nil or" and uncurry. "return" is trivial to implement.