Skip to content

Instantly share code, notes, and snippets.

@fogus
Created July 23, 2009 14:42
Show Gist options
  • Save fogus/153011 to your computer and use it in GitHub Desktop.
Save fogus/153011 to your computer and use it in GitHub Desktop.
/*
{} // map literal syntax
() // tuple literal syntax
|| // set literal syntax
[] // list literal syntax
foo // a symbol
"foo" // a string
foo => bar // a pair
:. // a block (similar to progn)
= // bind
~ // merge
<~ // merge bind
? // property query
foo(42) // symbol followed by a tuple is a function call
foo.fun() // call a method
foo fun() // call a method
$ // similar to `this` or `self`
foo {} // function followed by map is same as foo({})
foo:. // function followed by a block is same as foo(:.)
*/
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 special object `notset`
baz.n = 138 // sets property `n`
baz() // prints 138
def qux = {||=> baz.||} // grab the body of arity0 function
qux() // returns special object `notset`
qux <~ foo // foo has `n`, so merge it in (all of foo)
qux() // prints 42
qux.n = baz.n // set qux.n to baz.n
qux() // prints 138
qux <~ {|x| => [
print($.n - x) // merge in a new arity1 function
]}
qux(100) // prints 38
qux <~ {|x| => [
{|y| => [x + y]}
]} // merge in a new arity1 function
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 -- closed vars not accessible
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