diff --git a/examples/quicksort.zrc b/examples/quicksort.zrc new file mode 100755 index 0000000..af1fe02 --- /dev/null +++ b/examples/quicksort.zrc @@ -0,0 +1,46 @@ +#!../bin/zrc +%include list + +fn quicksort { + let {m pivot less equal greater vn x} { + set m = $argv(1) + # Bail out if only one elem in list + if {[llength $m] <= 1} { + return $m + } + + set pivot = [lindex $m 0] + set less = [set equal := [set greater := [list]]] + + # Iterate through list + foreach x {*}$m { + set x = [subst $x] + echo 'x=$x, pivot=$pivot' + + # See what var to dereference + # (leq, eq or geq) + switch [expr {$x <=> $pivot}] { + case -1 { set vn = 'less' } + case 0 { set vn = 'equal' } + case 1 { set vn = 'greater' } + } + set $vn = '$$vn $x' + } + return " + [quicksort $less] + $equal + [quicksort $greater]" + } +} + +set L = {8 6 4 2 1 3 5 7 9} + +# Main routine +fn main { + set L = [quicksort $L] + foreach x {*}$L { + echo -n [subst $x] ' ' + } + echo + return 0 +}; main