Friday, May 16, 2008

Purpose

The purpose of this blog is going to be me showing side by side all (well maybe not the ray tracer...) of the exercises from Paul Grahams ANSI Common Lisp in both CLisp and PHP. I will be creating a number of "helper" classes etc. to make the PHP side of things more livable (including a way of caching anonymous functions and thus not ending up with memory leaks... I think).

For now here are some examples of my Fluent Hash class in action with some list comprehension comparisons to python and lisp.


Note that xH and xR are shortcuts for creating a "new Hash" or creating a new hash
and immediately calling it's range method i.e
$new = new Hash();
$new->range(10);

/* python versions
S = [x**2 for x in range(10)]
V = [2**i for i in range(13)]
M = [x for x in S if x % 2 == 0]
P = [str(round(355/113.0, i)) for i in range(1,6)]
F = [x.strip() for x in [' banana', ' loganberry ']]
VEC = [2, 4, 6]
X = [3*x for x in vec if x > 3]
X1 = [[x,x**2] for x in vec]
*/

//PHP
$S = xR(10)->for_each('pow($x,2)');
$V = xR(13)->for_each('pow(2,$x)');
$M = xH($S)->if_only('$x % 2 == 0');
$P = xR(1,6)->for_each('round(355/113.0,$x)');
$F = xH(' banana', ' loganberry ')->map('trim');
$VEC = xH(2,4,6);
$X = xH($VEC)->if_only('$x > 3')->for_each('3*$x');
$X1 = xH($VEC)->for_each('Array($x,pow($x,2))');

/*common lisp
(loop for x from 0 to 100 if (> (* x x) 3) collect (* 2 x))
*/

//PHP
$C = xR(100)->if_only('($x*$x) > 3')->for_each('2*$x');


Now I am wondering if if_x and for_x would work equally well semantically... It would save a few characters but really I feel if_only and for_each are pretty verbose/explicit. One issue is map takes the name of a callback where as for_each takes the body and wraps map.. so semantically for_each should be for_eachu or something to denote it is a user defined function body expected/passsed... OR maybe for_each taking a body and map taking a function actually makes more sense in the first place!?

1 comment:

Paddy Mullen said...

Wow this seems cool, and hard, but why? Do you have to use php in your day job?