Monads are a way to chain functions together. Maybe monad (from Haskell) is used to chain functions together when the functions might fail. It assumes:
- If I have Nothing, stop computing.
- If I have Something, pass it to next function.
- That function may return Something or Nothing. Go back to Step 1.
x ||= y # x = y unless x
x &&= y # x = y if x
def open_connection_or_nil(addr, password)
c = get_host_by_name_or_nil(addr)
c &&= Connection.new(c) # c = Connection.new(c) if c
c &&= ConnectionDecrypter.new(c, password)
end
Rules of Maybe values:
- If Nothing and Nothing, choose Nothing.
- If Something and Nothing, choose Something.
- If Something and Something, choose first Something.
class Object
def mbind(&k)
k.call(self)
end
end
class << nil
def mbind(&k)
nil
end
end
1.mbind {|x| x.mbind {|y| puts y }} #=> 1
nil.mbind {|x| x.mbind {|y| puts y }} #=> nil
class Array
# If list if empty return empty list.
# Else pass each value in list to next function, it will return list.
#
def mbind(&k)
self.map {|v| k.call(v)}.flatten(1)
end
end
[1,2,3].mbind {|i| [i, i*10]} #=> [1,10,2,20,3,30]
Source: http://dave.fayr.am/posts/2011-10-4-rubyists-already-use-monadic-patterns.html
"A type with a monad structure defines what it means to chain operations of that type together."
Source: https://en.wikipedia.org/wiki/Monad_%28functional_programming%29
A language with Nil Punning has a rule that states something like, “Every value except Null (and false) are considered true.
self.class.new
and self.new
(which "just new" is) call new on different objects, except when self is Object.
See http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol
See https://github.com/mongodb/mongo-ruby-driver/blob/master/lib/mongo/networking.rb#L59-L93
var stdout = process.stdout;
var readline = require('readline');
var repl = readline.createInterface({
input: process.stdin,
output: stdout
});
repl.setPrompt('> ');
repl.prompt();
process.on("uncaughtException", function (error) {
stdout.write(error.stack);
});
repl.on('line', function(cmd) {
console.log(eval(cmd));
});
BSON is used to send commands to Mongo and store documents in disk.