Skip to content

Instantly share code, notes, and snippets.

@fogus
Created July 23, 2009 14:52
Show Gist options
  • Save fogus/153031 to your computer and use it in GitHub Desktop.
Save fogus/153031 to your computer and use it in GitHub Desktop.
def foo = {} // start with an empty map
foo.n = 42 // put a property
foo.z = 0
foo?n // does foo have property n?
foo.n // lookup property n
def bar = {|| => [print("Hello Cleveland")]}
bar() // prints Hello Cleveland
bar.|| // returns the list `[print("Hello Cleveland")]`
bar?() // does this function accept zero args?
bar.||.first() // returns the symbol `print`
def baz = {|| => [print($.n)]}
baz() // returns notset
baz.n = 138 // sets property `n`
baz() // prints 138
def qux = {||=> baz.||} // grab function body
qux() // returns object notset
qux <~ foo // foo has `n`
qux() // prints 42
qux.n = baz.n // set qux.n to baz.n
qux() // prints 138
qux <~ {|x| => [
print($.n - x) // merge arity1 fun
]}
qux(100) // prints 38
qux <~ {|x| => [
{|y| => [x + y]}
]} // merge arity1 fun
def frob = {}
frob <~ {
|| => [print("arity0")]
|x| => [print("arity1")]
|x y| => [print("arity2")]
}
frob() // prints "arity0"
frob(2) // prints "arity1"
frob(3 4) // prints "arity2"
def add2 = qux(2)
add2 // Lexical closure
add2.|_| // returns list `[$.x + y]`
add2?x // false - `x` is closed
add2(10) // returns 12
/** Multimethods **/
def mm = multimethod // set as prototypal defmulti object
mm.on // returns the default dispatch function
mm.on // {|_| => [_.class]}
mm.on?Object // is there a method for Object? true
mm.on.Object // {|_| => [_]}
mm.on.Object = method {|_| => [_.str()]}
mm(42) // returns "42"
mm.on.Number = method {|_| => [_ + 2)]}
mm(10) // returns 12
mm([1 2]) // returns "[1 2]"
mm.on.List = method {|_| => _.length()}
mm([1 2]) // returns 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment