Skip to content

Instantly share code, notes, and snippets.

@sent-hil
Created October 4, 2012 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sent-hil/3834447 to your computer and use it in GitHub Desktop.
Save sent-hil/3834447 to your computer and use it in GitHub Desktop.
HS: +3 Monad and Gonads

Monads

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:

  1. If I have Nothing, stop computing.
  2. If I have Something, pass it to next function.
  3. 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:

  1. If Nothing and Nothing, choose Nothing.
  2. If Something and Nothing, choose Something.
  3. 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

Nil Punning

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

self.class.new and self.new (which "just new" is) call new on different objects, except when self is Object.

Connecting to Mongo via sockets

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

Repl in Node

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

BSON is used to send commands to Mongo and store documents in disk.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment