Exec-tree-example.pl

From Organic Design wiki
Revision as of 13:10, 8 December 2011 by Nad (talk | contribs) (Category:PERL)

Example of nodal reduction in Perl. <perl>

  1. !/usr/bin/perl -w

use strict;

  1. First, we set up three test threads each of three sequencial functions
  2. - Each function simply prints its name and returns a reference to the next in its thread
  3. - In reality the functions would be acting on their local environment
  4. (in PERL the local environment is in the global $cwd hashRef)
  5. - and what's returned can be not only a function, but another hashRef or void if its finished

our ($A,$B,$C, $P,$Q,$R, $X,$Y,$Z); $A = sub {print "A"; return $B;}; $B = sub {print "B"; return $C;}; $C = sub {print "C"; return $A;};

$P = sub {print "P"; return $Q;}; $Q = sub {print "Q"; return $R;}; $R = sub {print "R"; return $P;};

$X = sub {print "X"; return $Y;}; $Y = sub {print "Y"; return $Z;}; $Z = sub {print "Z"; return $X;};

  1. The execution tree is set up with the root containing thread-ABC
  2. and another node which contains threads PQR & XYZ
  3. - So PQR and XYZ execute in parallel and as a whole they execute in parallel with ABC

my $someNode = {queue => [$P,$X]}; my $root = {queue => [$A,$someNode]}; our $cwd; # In PERL the functions act on their local environment which is the $cwd hashRef

while (1) { $cwd = $root; for (my $i = 1; $i == 1;) { my $queue = $$cwd{'queue'}; if ($#$queue >= 0) { my $todo = shift @$queue; push @$queue, $_ if $_ = (ref $todo eq 'CODE') ? ($i = &$todo) : ($cwd = $todo); } else {$i = 0} } } </perl>