Independently discovering Option.map and realizing its usefulness is good. Point at the existing work instead of making fun.
http://en.wikipedia.org/wiki/Option_type (well.. maybe a bit more introductory than that..)
These semantics are basically what you implement by hand when you join together computations that may produce NULL results and check for NULLs in between. But now the computer is doing the checking for you, so the checking is hidden and yet never gets forgotten.
For example, here's some Haskell code the provides a simple lookup database from names (type "a") to phone numbers (type "b"):
-- name phone number
persons = [("Joe", "123-555-7890"),
("Tom", "432-555-0987")]
The lookup service for this database may return a result, thus it returns a value of the Maybe type to indicate that it may not be able to find a "b" for every "a" you give it: lookup :: Eq a => a -> [(a, b)] -> Maybe b
But since Maybe is a monad and its bind rule takes care of the didn't-get-a-result checking for us, we can safely string together lookup computations without having to do any checks by hand. Nevertheless, we can be assured that all the checks will be done.For example, let's create a function that takes two persons' names, looks up their phone numbers, and (if both are found) connects them with a (simulated) call.
-- try to connect person a's phone to person b's phone
connect a b = do
phonea <- lookup a persons
phoneb <- lookup b persons
return $ "connected " ++ phonea ++ " to " ++ phoneb
If we try to connect two names that are known to our lookup service, the call goes through as expected: *Main> connect "Tom" "Joe"
Just "connected 432-555-0987 to 123-555-7890"
But if either or both of the name lookups fail, no call is made: *Main> connect "Tom" "SomeUnknownDude"
Nothing
*Main> connect "SomeUnknownDude" "Tom"
Nothing
*Main> connect "SomeUnknownDude" "AnotherUnknownDude"
NothingThe 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.Sounds like programmable semicolon, or a monad, to me.