All pastes #814297 Raw Edit

k4st

public text v1 · immutable
·published 2007-12-13 04:14 UTC
rendered paste body

/* Syntax for quickly typed simple functions and more involved functions by
   returning a language construct 
 */

simple(x) => x+2  /* simple named function, implicit return */

complex(x) => do: /* named function that uses the "do" language construct to
                     allow for more expressions/statements.
                   */
	x = x+2
	return x
;

lambda = (x) => x+2 /* example of lambda (anonymous/unnamed) functions

/* Procedures work in a very similar way. Procedures are like functions, they
   simply don't have arguments (unless a procedure points to an anonymous
   function). More to the point, functions *are* procedures, they just allow
   for arguments to be passed to them. For example:
 */

x => 1 /* similar to x = 1, except that x returns one instead of actually 
          being one. This means that x cannot be incremented in the same way
          that a normal variable x could be. It also means that every time
          x is accessed, it will return 1. This leads to further conclusions:
        */

x => do:
	/* a procedure in here */
;

/* The following do the same thing, if not in a slightly different way. */
add_one => (x) => x+1 /* returns a function, thus can be used as a function */
add_one(x) => x+1 /* is a function */
add_one = (x) => x+1 /* variable named anonymous function */

/* Altho it is not immediately evident, this style of procedure is immensely
   useful.
 */

many_args(...) => do:
	return args /* array of arguments */
;

/* Example of an iterator, notice how a language construct is returned. The
   yield keyword is like a return, where it stops the loop, but allows the
   loop to be resumed at a later time.
 */
ArrayIterator(some_array) => for elem in some_array:
	yield elem
;

/* Object from dictionary, dictionaries can be accessed using the '.' notation 
   assuming there are valid characters in them. Do not confuse this with real 
   objects!
 */
Object(d:dict={}) => do:
	this = d
	
	if !("construct" in this):
		this.construct = () => null
	;
	
	return (...) => do:
		apply(this.construct, args)
		return this
	;
;

/* The following show how to 1) create an 'object' that whenever called
   (instantiated) will have its own state; and 2) how to create an object
   that whenever called will share its state with all calls to that object.
 *
   This shows that objects aren't really instantiated at all; they are simply
   scoped closure tricks that encapsulate state.
 */

Class(d) => (...) => apply(Object(d), args)
Singleton = Object

/* Application of class and singleton is now uses the same general form but
   has a wildly different meaning.
 */

Stack = Class({
	/* ... */
})

Registry = Singleton({
	/* ... */
})