From 018379b0cf4e286ceacb1e39f34dd80f770e381e Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Mon, 21 Apr 2025 14:18:23 -0700 Subject: Chapter 22: A Hello, World! MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: godalming123 <68993177+godalming123@users.noreply.github.com> Co-authored-by: Tamás Hadházy <85063808+Hels15@users.noreply.github.com> --- docs/chapter22/examples/A_helloWorld.smp | 3 + docs/chapter22/examples/BubbleSort.smp | 109 +++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 docs/chapter22/examples/A_helloWorld.smp create mode 100644 docs/chapter22/examples/BubbleSort.smp (limited to 'docs/chapter22/examples') diff --git a/docs/chapter22/examples/A_helloWorld.smp b/docs/chapter22/examples/A_helloWorld.smp new file mode 100644 index 00000000..07ff935f --- /dev/null +++ b/docs/chapter22/examples/A_helloWorld.smp @@ -0,0 +1,3 @@ +// -*- mode: java; -*- +sys.io.p("Hello, World!"); +return 0; diff --git a/docs/chapter22/examples/BubbleSort.smp b/docs/chapter22/examples/BubbleSort.smp new file mode 100644 index 00000000..aa9cbbb8 --- /dev/null +++ b/docs/chapter22/examples/BubbleSort.smp @@ -0,0 +1,109 @@ +// -*- mode: java; -*- + +// An implementation of +// https://sampleprograms.io/projects/bubble-sort/ +// +// Bubble sort, with reading (parsing) and writing (formatting) the data. + + +val _exit = { u8[~] msg -> + sys.io.p(msg); + sys.libc._exit(1); +}; + +val usage = { -> _exit("stdin must look like [4, 3, 2, 1]"); }; + +// Scanner +struct Scan { + int !x; + u8[~] buf; +}; + +// Skip whitespace +val skip = { Scan s -> + while( s.buf[s.x] <= ' ' ) + s.x++; +}; + + +// Require specific syntax or usage +val require = { Scan s, u8 c -> + skip(s); + if( s.buf[s.x++] != c ) + usage(); +}; + +val peek = { Scan s, u8 c -> + skip(s); + if( s.buf[s.x] != c ) return false; + s.x++; + return true; +}; + +val number = { Scan s -> + skip(s); + i32 n = 0; + while( '0' <= s.buf[s.x] & s.buf[s.x] <= '9' ) + n = n*10 + (s.buf[s.x++] - '0'); + return n; +}; + +val sort = { int[] ns, int len -> + var done = false; + while( !done ) { + done = true; + for( var i = 0; i < len-1; i++ ) + if( ns[i] > ns[i+1] ) { + int tmp = ns[i]; + ns[i] = ns[i+1]; + ns[i+1] = tmp; // Swap + done = false; + } + } +}; + +// Read from stdin a line of the form "[ 4, 3, 2, 1]" and print it sorted. +val main = { -> + Scan !s = new Scan{ buf = sys.io.stdin(); }; + require(s,'['); + // Array of parsed results + int[] !ns = new int[16]; + i32 len = 0; + // Parse a list of numbers + if( !peek(s,']') ) { // Handle the empty list + // Parse "123, " until a something else + while( s.x < s.buf# ) { + int n = number(s); + ns[len++] = n; + if( !peek(s,',') ) + break; + }; + require(s,']'); // Close the list + } + + // Bubble sort array of integers + sort(ns,len); + + // Print a list of numbers + sys.io.p("[ "); + u8[] !junk = new u8[1]; + for( int i=0; i