Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Forth use IF statement THEN ... instead of ENDIF? [closed]

Why does Forth use IF statement THEN ... instead of ENDIF?

I'm implementing a (non-conforming) Forth compiler thing. Basically, Forth's syntax appears very counter-intuitive to me regarding IF statements.

IF ."Statement is true"
ELSE ."Statement is not true"
THEN ."Printed no matter what;

Why is the ending statement a THEN? This makes the language read extremely weird to me. For my compiler, I'm considering changing it to something like ENDIF which reads more natural. But, what was the rationale behind having backwards IF-THEN statements in the first place?

like image 657
Earlz Avatar asked Sep 22 '12 00:09

Earlz


People also ask

Why do we use end if?

An ENDIF statement always follows the ELSE clause, if present, or the THEN clause. The THEN clause specifies the job steps that the system processes when the evaluation of the relational-expression for the IF statement is a true condition. The system evaluates the relational-expression at execution time.

Which type of IF statement requires an end if '?

END IF is invalid for the IF, ELSE IF, ELSE statements written in one line. Any statement in the next line will be considered out of the IF, ELSE IF, ELSE structure. It is not always possible to code all of the required functionality in one line.

What is the end after IF statement?

An IF statement is executed based on the occurrence of a certain condition. IF statements must begin with the keyword IF and terminate with the keyword END. Components within IF statements can be connected with the keywords AND or OR.

Does Python have endif?

Yes. Python uses indentation to mark blocks. Both the if and the for end there. It means "power", or what in some languages is ^ (Python uses that for bitwise xor).


1 Answers

Just think of it as, "IF that's the case, do this, ELSE do that ... and THEN continue with ..."

Or better yet, use quotations (as in Factor, RetroForth, ...) in which case it's completely postfix without special compile-time words; just regular words taking addresses from the stack: [ do this ] [ do that ] if or [ do this ] when or [ do that ] unless. I personally much prefer this.

Aside RE: quotations

Here is how quotations are compiled in RetroForth. In my own Forth (which compiles to my own VM), I simply added a QUOTE instruction that pushes the next address to the stack and jumps over n-bytes. The n-bytes are expected to be terminated by a RETURN instruction and the if, when, unless words consume a predicate along with the address(es) left by preceding quotations; calling as appropriate. Very simple indeed, and quotations generally open the door for all kinds of beautiful abstractions away from thinking about the stack.

like image 140
AshleyF Avatar answered Oct 13 '22 14:10

AshleyF