Saturday, November 17, 2018

Make a Crude Triangle in Forth

In programming related on-line communities, sometimes students come asking for solutions to their programming problems.

Sometimes we like to be very helpful.

Recently, in the Not Just Tiny-C Facebook group, we had a pair asking for help writing a C program to make right triangles using (monospaced) character output on a terminal console, something like this:

*
**
* *
*  *
*   *
*    *
*     *
*      *
*       *
**********

Part of their assignment was to use a do while C loop.

Part of their assignment was to get the size of the triangle from the terminal input.

We gave them a few hints. And I refrained, at the time, from giving them the trivial tutorial solution in Forth. (This is a traditional tutorial problem, you see.)

Well, here is one typical version of the traditional trivial solution in Forth, with some tests mixed in to help the uninitiate.

Except.

Forth handles the conversion from terminal input to numeric for you. So that part of the solution is opaque.

And I used the traditional Forth counted loop instead of the Forth do while loop. (Forth do while loops don't translate to C do while loops unless you know both pretty well, anyway.)

(Tested in gforth and fig-Forth. Copy and paste, it should run as-is in quite a variety of Forths.)

--------------
: star ( --- ) ( Very traditional tutorial word! )
  42 emit ; 
star
: stars ( n --- ) ( Refining tradition a little. )
  dup 0 > 0= if
    drop
  else
    0 do
      star
    loop
  endif ;
0 stars
1 stars
2 stars
3 stars 
: bracket ( n --- )
  star dup 2 < if
    drop
  else
    2 - spaces star
  endif ;
0 bracket
1 bracket
2 bracket
3 bracket
10 bracket
: triangle-bottom ( n --- )
  cr dup 1 > if
    dup 1 do
      i bracket cr
    loop
  endif
  stars cr ;
: triangle ( n --- )
  dup 0 > 0= if
   drop
  else
    triangle-bottom
  endif ;
0 triangle
1 triangle
2 triangle
3 triangle
4 triangle
10 triangle

--------------

Now isn't that just more fun than you've had all week?