Search code examples
code-formattingforth

Forth code formatting guide


I am trying to teach myself Forth by doing Project Euler exercises. I've looked into several tutorials, but I couldn't find any definitive guide as to how to position keywords / control structures. Emacs forth-mode seems to have some idea about how the code should be formatted, but I am not really convinced about what I see :) So, for example, the code below:

: euler1
    0 1000 0
    do i dup 3 mod -rot 5 mod -rot -rot * 0=
        if i + then
    loop ;

Does it make sense to format it this way? Where'd you put conditions? If there's any kind of style guide / a collection of examples, which, you believe, are properly formatted, could you please refer me to that example?


Solution

  • If you mean formatting in the sense of where the whitespace should go, your example seems pretty reasonable; indentation for loops and words makes the code fairly readable for people more used to languages where indentation or brackets are required.

    My style preference would be more like the code below, but I am not sure what you code is doing so I may have arranged it in a way that does not make perfect sense. In general I would put the conditions for a conditional on a new line along with the keyword, and if the condition is complicated I would factor it out into its own word (add-i? below).

    : add-i?
        dup 3 mod -rot 5 mod -rot -rot * 0= ;
    
    : euler1
        0 
        1000 0 do
            i add-i? if 
                i + 
            then
        loop ;
    

    It can be a little unintuitive to have the starting keyword of a conditional block or loop at the end of the first line, but I sort of think of it as a visual cue similar to the way Python uses a : to enter an indented region (or how Visual Basic uses Then (see the second example)), e.g.

    if true:
        print("True")
    

    The thens and loops are the equivalents of closing curly brackets or keywords like End If in Visual Basic e.g.

     If True Then
         MsgBox "True"
     End If
    

    (which is a slightly confusing example as the use of Then is different to its use in Forth)