All pastes #814195 Raw Edit

k4st

public text v1 · immutable
·published 2007-12-13 01:49 UTC
rendered paste body

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

simple(x) => x+2

complex(x) => do:
	x = x+2
	return x
;

/* 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). 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 */
;
add_one => (x) => x+1 /* returns 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
	;
;

/* For an "object" to work, it needs to be created within a new state, meaning
   that everytime 'ArrayIterator' is used, Object is called and returned. It
   has to be within a procedure because otherwise every ArrayIterator would
   share 'instance' variables, because of 'static' scoping.
   
   Regardless, array iterators such as the one below are redundant given the
   assumption that the previous array iterator example with the for loop would
   work. This is merely an example of how it would look as an "object".
 */
ArrayIterator => Object({
	
	ls: null,
	ln: 0,
	i: -1,
	
	construct: (ls:list) => do:
		this.ls = ls;
		this.ln = length(ls)
	;,
	next: () => do:
		this.i++;
		
		return (this.i < this.ln)
	;,
	current: () => do:
		return this.ls[this.i]
	;,
	rewind: () => do:
		this.i = 0;
	;
})

it = ArrayIterator([1,2,3,4,5]);

/* Making a singleton is actually extremely easy. Instead of using a
   procedure, we use Object directly.
 */
SingletonObject = Object({
	/* class definition in here */
})