Created
July 23, 2009 14:57
-
-
Save fogus/153045 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 `[print("Hello Cleveland")]` | |
bar?() // accepts 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 // prototypal defmulti object | |
mm.on // default dispatch function | |
mm.on // {|_| => [_.class]} | |
mm.on?Object // has 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