From 965ab21953a5ef419924173ea913ff023a5a5739 Mon Sep 17 00:00:00 2001 From: antirez Date: Mon, 30 Jan 2023 11:45:55 +0100 Subject: [PATCH] Add a few example programs. --- aocla.c | 2 +- examples/cat.aocla | 11 +++++++++++ examples/firstrest.aocla | 21 +++++++++++++++++++++ examples/foreach.aocla | 14 ++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 examples/cat.aocla create mode 100644 examples/firstrest.aocla create mode 100644 examples/foreach.aocla diff --git a/aocla.c b/aocla.c index 22a595d..86fddda 100644 --- a/aocla.c +++ b/aocla.c @@ -1047,7 +1047,7 @@ void loadLibrary(aoclactx *ctx) { addProcString(ctx,"drop","[(_)]"); /* [1 2 3] [dup *] map => [1 4 9] */ - addProcString(ctx,"map", "[(l f) $l len (e) 0 (j) [] [$j $e <] [ $l $j get@ $f upeval swap -> $j 1 + (j)] while]"); + addProcString(ctx,"map", "[(l f) $l len (e) 0 (j) [] [$j $e <] [$l $j get@ $f upeval swap -> $j 1 + (j)] while]"); /* [1 2 3] [printnl] foreach */ addProcString(ctx,"foreach"," [(l f) $l len (e) 0 (j) [$j $e <] [$l $j get@ $f upeval $j 1 + (j)] while]"); diff --git a/examples/cat.aocla b/examples/cat.aocla new file mode 100644 index 0000000..fa9f773 --- /dev/null +++ b/examples/cat.aocla @@ -0,0 +1,11 @@ +// List concatenation. This procedure is part of the standard +// library. + +// [1 2 3] [4 5 6] cat => [1 2 3 4 5 6] +[(a b) + $b [$a -> (a)] foreach + $a +] 'cat def + +[1 2 3] [4 5 6] cat +showstack diff --git a/examples/firstrest.aocla b/examples/firstrest.aocla new file mode 100644 index 0000000..35b295c --- /dev/null +++ b/examples/firstrest.aocla @@ -0,0 +1,21 @@ +// Fundamental list manipulation functions. Part of the standard library. +// first, rest, cat + +[ + 0 get@ +] 'first def + +[ + #t (f) // True only for the first element + [] (n) // New list + [ + [$f] [ + #f (f) // Set flag to false + drop // Discard first element + ] [ + $n -> (n) + ] ifelse + ] foreach + $n +] 'rest def + diff --git a/examples/foreach.aocla b/examples/foreach.aocla new file mode 100644 index 0000000..14d0a4a --- /dev/null +++ b/examples/foreach.aocla @@ -0,0 +1,14 @@ +// This is a commented version of the implementation of 'foreach' inside +// the standard library. + +[(l f) // list and function to call with each element. + $l len (e) // Get list len in "e" + 0 (j) // j is our current index + [$j $e <] [ + $l $j get@ // Get list[j] + $f upeval // We want to evaluate in the context of the caller + $j 1 + (j) // Go to the next index + ] while +] 'foreach def + +[1 2 3] [printnl] foreach