J2MCK


                То, что останавливает -- это не обязательно страх.
                
                Тормоз. (новое это хорошо забытое старое, 2012)

# СТЕК, RPN, ОПЕРАЦИИ

Для того, чтобы захотелось изучить что-то новое, необходимо четко представлять себе: зачем мне это нужно ?


# ИТАЛЬЯНСКИЙ LOGISIM (важно: живой и обновляется (2019.02.21))

  http://www.logisim.altervista.org/
  https://github.com/LogisimIt/Logisim
  
1. Очередь: FIFO (first in, first out). Примеры:

   Елка в трубке: засовываем с одной стороны, вынимаем с другой
   
   Тюбик с зубной пастой: Заполняем с одной стороны, выдавливам с другой
   
Построить очередь 6 х 1 (length x width)
Кнопки: PUSH (iN), POP (oUT), DATA
  
2. Стек: LIFO (last in, first out). Примеры:

Построить стек 6 x 1 (depth x width). 
Кнопки: PUSH (PUT), POP (GET), DATA


# ОПЕРАЦИИ
  
  stack:   top [ 5 2 3 < + 7 -       ] bottom 
  result:  -1 
  infix:   ( 5 + ( 2 < 3 ) ) - 7
  
Онлайн конвертер на 4 действия здесь:

  https://www.mathblog.dk/tools/infix-postfix-converter/
  
Желательно не захламлять стек и производить операцию, как только в стеке будет достаточно данных.

  stack:   top [ 2 3 < 5 + 7 -       ] bottom 
  result:  -1 
  infix:   ( ( 2 < 3 ) + 5 ) - 7

Будем использовать 22 операции

  Арифметика (7): +  -  *  /  %  u- ** 
  Биты (6):       ~  &  |  ^  >> <<
  Сравнения (5):  <  <= == >= >        вернут 0 если нет 1 если да
  Логика (3):     !  && ||
  Тринити (1):    ?:
  
В очень упрощенном коде -- одна операция это один символ. Например так:

          +  это +    ~  это ~    <  это <    !  это !
          -  это -    &  это &    <= это {    && это u
          *  это x    |  это |    == это E    || это o
          /  это /    ^  это ^    >= это }
          %  это %    >> это R    >  это >    ?: это T
          ** это P    << это L               POP это G (get)
  унарный -  это m
  
Комментарий специалиста:) 

     PUSH, means PUT. Cлово можно не писать.
  G  POP, means GET
  x  означает умножить
  P  means POWER
  m  от слова минус, заглавные русская М и латинская M 
     выглядят одинаково хотя коды символов разные и это ужасно:)
  R  right shift, не путать с "Red Shift" (физика)
  L  left shift
  E  means equal
  U  bedeutet UND, nicht mathematisches U, 
     was bedeutet ODER stattdessen
  o  bedeutet ODER 
  T  means trinary (Trinity)


# РОБОТ С КОРОТКОЙ ПАМЯТЬЮ ИЛИ КАК РАБОТАЕТ ОПЕРАЦИЯ СО СТЕКОМ

Унарная, например логическое НЕ:  

  ! 5

       состояние стека  (0 3 8 уже были в стеке, 5 ! это команда ! 5)
  дно [     0 3 8 5 ! ] вершина
     
      [       0 3 8 5 ] POP, вынули команду logical not из стека. 
      [         0 3 8 ] POP, вынули число 5, accumulator = 5
      [         0 3 8 ] произвели операцию !5 в аккумуляторе, ответ 0
      [       0 3 8 0 ] PUSH 0, положили результат на стек.

Бинарная, например вычитание:

       состояние стека   
  дно [         8 5 - ] вершина
     
      [           8 5 ] POP, вынули команду вычитания из стека. 
      [             8 ] POP, вынули число 5, accumulator = 5
      [               ] произвели операцию, стек пустой, 
                        ответ (3) в аккумуляторе
      [             3 ] PUSH, положили результат на стек.
  
Комментарий сторонника мирового эфира:) 

Почему всё как-то по арабски (справа налево)? А тогда почему 6 - 7 а не 7 - 6 (а здесь вдруг слева направо)?

У автора (Ян Лукасевич) было все как надо (польская запись), но перевернули (RPN, reverse polish notation), сославшись на то, что автор был левшой. Проверили второй закон термодинамики.. Он работает! В эпоху компьютеров (после смерти автора (1878-1956)) именно вариант с RPN стал очень популярным (модным).


# ЧТО ЕСТЬ ЧТО, ИЛИ ПРОВЕКА БАШЕМ (BASH)

BASH вычисляет инфиксные выражения -- т.е как в школе, нужно помнить приоритеты операций (22 (+ - .. ?:) это больше чем 4 (+ - x /)), и ставить много-много скобок, например 

  50*((2<3)+(2>3))%((2>=1)+(0==0))**2).

ВАSH делит нацело (оставаясь в кольце), ZSH может вычислять в рациональных числах (вылетает в поле):

  # echo $(( 5 / 2 ))
  2
  $ echo 'print $(( 5 / 2 ))' | zsh
  2
  $ echo 'print $(( 5. / 2 ))' | zsh
  2.5

Операции

  +  сложение           echo $(( 13 +  5 ))    18
  -  вычитание          echo $(( 13 -  5 ))    8
  *  умножение          echo $(( 13 *  5 ))    60
  *  деление нацело     echo $(( 13 /  5 ))    2
  %  остаток от деления echo $(( 13 %  5 ))    3
  -  унарный минус      echo $((    - -5 ))    5   (дополнительный код!)
  ** степень            echo $(( 13 ** 5 ))    371293
  
  ~  bitwise NOT        echo $((     ~13 ))    -14 (unary. C2)
  &  bitwise AND        echo $(( 13 &  6 ))    4   (1101 & 0110 = 0100)
  |  bitwise OR         echo $(( 12 |  6 ))    14  (1100 | 0110 = 1110)
  ^  bitwise XOR        echo $(( 12 ^  6 ))    10  (1100 ^ 0110 = 1010)
  << сдвиг влево        echo $(( 13 << 2 ))    52
  >> сдвиг вправо       echo $(( 13 >> 2 ))    3

  <  меньше             echo $(( 13 <  5 ))    0
  <= меньше или равны   echo $(( 13 <= 5 ))    0
  == равны ли           echo $(( 13 == 5 ))    0
  >= больше или равны   echo $(( 13 >= 5 ))    1
  >  больше             echo $(( 13 >  5 ))    1

  !  логический не      echo $((     ! 5 ))    3   (*, унарный)
  && логический "И"     echo $(( 13 && 5 ))    1   (*)
  || логический "ИЛИ"   echo $(( 0  || 7 ))    1   (*)
  
  ?: if, then, else     echo $(( 13 ? 5 : 4 )) 5   (*)
  
*) Все числа кроме нуля это истина. 


Комментарий специалиста:) 

  светло "И" тепло          светло "ИЛИ" тепло

  темно и холодно   нет     темно и холодно   нет
  темно и тепло     нет     темно и тепло     да
  светло и холодно  нет     светло и холодно  да
  светло и тепло    да      светло и тепло    да
  
-- Темно и сыро?
-- А какой default у температуры?
-- Вопросом на вопрос отвечать невежливо!
-- Тогда мой ответ: "не знаю (вылетаю из кольца: true, false, &&, ||, !)


                Если в темном коридоре не касаться стен -- 
                то можно так никогда и не узнать, 
                что стены вообще существуют.
  
# ОПЕРАЦИИ И ФУНКЦИИ.

Широко распространенная инфиксная запись типа 2 + 2 отсутствует, все  операции заменяются функциями, например, add( 2, 2). 


# HAIKU FORTH

1. double loop (for x and for y) on each frame -- main controller loop.
   Haiku code computes one pixel (x,y)

2. two stacks of type float: "data" (main) and "return" ( >r, r>, r@).
   return stack is just a traditional name currently used for data
   processing only (Брусенцов)

3. case insensitive ( for example X Y 2DUP * )

4. on each run on data stack program returns R G B A.
   Missing values replaced with zero (black opaque)

5. 16 float cells of RAM: 0..15 
   write operation ! is allowed only when x=0, y=0, 
   read operation @ is allowed always


   ^ y ( 0..1)           /* Main Controller Loop: */
   |                     for x in (0..1) {
 1 +......                 for y in (0..1) {
   |     .                   ( haiku code for single pixel at (x,y):
   |     .                     always read 0 from empty stack )
   +-----+--> x (0..1)       R G B A 
                         }}                                         

  Comments:     ( )  \                                            ( 2)

  Language:     : ;  if else then                                 ( 2)

  Put:          x  y  t  dt  mx  my  button  buttons  pi  random  (10)

  "Data":       dup  over  2dup  drop  swap  rot  -rot            ( 7)
  "Return":     >r  r>  r@                                        ( 3)
  RAM 0..F:     @  !                                              ( 2)

  Compare:      =  <>  <  >  <=  >=                               ( 6)

  Logic:        and  or  not                                      ( 3)

  Arithmetics:  + - * / mod ** negate abs  min  max               (10)

  Functions:    sin cos tan  atan2  log  exp  sqrt  floor  ceil   ( 9)

  Complex       z+ z*                                             ( 2)

*) NOTES: 

  1) RAM ! operation MOVES data away from stack
  2) .. if .. else .. then  actually means  .. if .. thenelse .. endif
  3) = means ==, because there is no = assignment in Haiku Forth

# Для изучения языка нам потребуется Туул, с помощью которого удается увидеть целую часть результата наших вычислений в диапазоне 0..255 в шестнадцaтеричном коде. Если на стеке кроме результата есть что-то еще, туул работает плохо (side effects, одно лишнее слово на стеке и меняется окрас, два или более лишних слова и туул не работает)

# Туул (исходник)

  ( * ============== The 7-TOOL ================== * )

  : 3dup     >r 2dup r@ -rot r> ;
  : offset   >r swap >r + r> r> + ;
  : between  >r swap dup >r <= r> r> < and ;
  : hor       >r .01 .09 between r> -.01 .01 between and ;
  : ver      >r -.01 .01 between r> .01 .09 between and ;
  : off      over <> r> and >r ;
  : sega     >r 0 -.2 offset hor r> 1 >r 
             1 off 4 off 11 off 13 off drop r> and ;
  : segb     >r -.1 -.1 offset ver r> 1 >r 
             5 off 6 off 11 off 12 off 14 off 15 off drop r> and ;
  : segc     >r -.1 0 offset ver r> 1 >r 
             2 off 12 off 14 off 15 off drop r> and ;
  : segd     >r hor r> 1 >r 
             1 off 4 off 7 off 9 off 10 off 15 off drop r> and ;
  : sege     >r ver r> 1 >r 
             1 off 3 off 4 off 5 off 7 off 9 off drop r> and ;
  : segf     >r 0 -.1 offset ver r> 1 >r 
             1 off 2 off 3 off 7 off 13 off drop r> and ;
  : segg     >r 0 -.1 offset hor r> 1 >r 
             0 off 1 off 7 off 12 off drop r> and ;
  : digit    3dup sega >r 
             3dup segb r> or >r 
             3dup segc r> or >r 
             3dup segd r> or >r 
             3dup sege r> or >r 
             3dup segf r> or >r 
             segg r> or ;
  : 2digit   3dup >r >r >r 16 / floor digit 
             r> .14 - r> r> 16 mod floor digit or ;
  : number   x .36 - swap y .4 - swap 2digit dup dup ;

  \ 0 2 3 ?: number
    1 2 3 ?: number

# ПЕРЕВОДЧИК

Мы начали знакомство с операциями и воспользовались для этого конструкцией echo $ (( выражение )) интерпретатора sh . Некоторые знакомые нам по sh операции имеют в haiku forth другие обозначения. Мы можем определить новые (для haiku forth) слова и построить переводчик: 

  : ==       = ;
  : &&       and ;
  : ||       or ;
  : %        mod ;
  : ?:       rot 0 == dup -rot * -rot not * + ;
  : thenelse else ;
  : endif    then ;
  

# РАБОЧАЯ ТЕТРАДКА

  1
  ( Red square )

---

  0 1
  ( Green square )

---

  0 0 1
  ( Blue square )

---

  x
  ( left black right red. )
  ( x is horiz, scans from 0 to 1 )

---

  y
  top red bottom black.
  y is vert, scans from 0 to 1

---

  ( chessboard )
  : xor + abs 2 mod ;
  x 8 * 2 mod 1 > y 8 * 2 mod 1 < xor not dup dup
  
---

Any Mouse button or "Q"

  ( Left mouse button paints the whole area to RED )
  0 button

---

Any mouse button or any key from list*:

  ( any mouse button paints the whole area to WHITE )
  buttons dup dup

*) See reference in Annex B

---

Mouse over

  mx  my


## LINKS
--------

  1. http://edu.alnam.ru/book_mav.php?id=17

  2. https://www.quaxio.com/forth_haiku/
  3. https://forthsalon.appspot.com/
  4. https://forthsalon.appspot.com/word-list
  
  5. http://www.forth.org/svfig/kk/11-2011-Nelson2.pdf
  

## ANNEX A
----------

file sm.c

  #include <time.h>
  #include <stdio.h>
  #include <stdlib.h>
  
  int other(int arand, int arem) {
    int newrand;
    do {
      newrand=rand()%arem;
    } while(arand==newrand);
    return newrand;
  }

  int main() {
    char* CMD[] = { 
      "POP",  
      "+",    "-",   "*",  "/", "%",  "**", "U-",
      "&",    "|",   "^",  "~", "<<", ">>",
      "&&",   "||",  "!",
      "<",    "<=",  "==", ">=", ">",
      "?:"
    };
    
    srand(time(NULL));
    
    printf("\nRPN machine with ACCUMULATOR STACK.\n"
      "Empty stack returns 0.\n\n"
    );
   
    printf("BOTTOM[  %d  ", rand()%16);
    for(int n=0; n<5+rand()%5; n++)
      printf("%d  %s  ", rand()%16, CMD[rand()%23]);

    printf(
      "]TOP\n\nResult is on top of the ACCUMULATOR STACK.\n"
      "Calculate or Save the World:\n"
      "Create simulator, print with POP\n\n"
    );
    return 0;
  }

EOF

# ANNEX B. HAIKU FORTH QUICK REFERENCE
--------------------------------------

Comments

(       A comment until the next ")".
\       A comment until the end of the line.

Operations: Arithmetics

+       Add the top two numbers on the stack.
-       Subtract the top element on the stack from the next element.
*       Multiple the top two elements on the stack.
/       Divide the second element on the stack by the top element.
mod     Find a mod b
**      (pow) Find a to the bth power.
negate  Negate the element on top of the stack (unary minus).

Operations: Logics

and     Find the logical "and" of the top two elements on the stack.
or      Find the logical "or" of the top two elements on the stack.
not     Find the logical "not" of the top two elements on the stack.

Operations: Compare

=       isEqual? 1 -- true, 0 -- false
<>      isNotEqual?
<       isLess?
>       isGreater?
<=      isLessEqual?
>=      isGreaterEqual?

Functions

: ;      Define a new word.

Built-in variables

x        Put the current x-coordinate on the stack
y        Put the current y-coordinate on the stack
t        Put the current time in seconds since midnight on the stack.
dt       Put the change in time since the last frame in seconds on the stack.
mx       Put the current x-coordinate of the mouse on the stack.
my       Put the current y-coordinate of the mouse on the stack.
button   Put the state of a given button on the stack.
buttons  Put the state of several buttons on the stack.
pi       Push pi onto the stack
random   Return a pseudo-random number in the range [0, 1).

Alien

@   Read the value at a memory address.
!   Store a value to a memory address.
?:  if then else

Brusentsov:

>r  (or push) MOVES (not copies) one value from the data stack to the return stack.
r>  (or pop)  MOVES (not copies) one value from the return stack to the data stack.
r@  Copy the top value from the return stack to the data stack.

Forth dimension:

dup     Duplicate the element on top of the stack.
over    Duplicate the element under the top stack element.
2dup    Duplicate the top two elements on the stack.
drop    Drop the top element from the stack.
swap    Swap the top two elements on the stack.
rot     Rotate the top three two elements on the stack [012..]-->[120..]
-rot    Reverse rotate the top three elements on the stack  [012..]-->[201..]

API

min     Select the smaller of the top two stack elements.
max     Select the larger of the top two stack elements.
abs     Compute the absolute value of the number on top of the stack.
floor   Round the number on top of the stack downward.
ceil    Round the number on top of the stack upward.

atan2   Find the arctangent of a/b.
sin     Compute the sine of the top element of the stack.
cos     Compute the cosine of the top element of the stack.
tan     Compute the tangent the top element of the stack.
log     Compute the log base e of the top element of the stack.
exp     Compute e raised to the power on top of the stack.
sqrt    Compute the square root of the top element on the stack.


# ANNEX C. HAIKU FORTH REFERENCE GUIDE
--------------------------------------

  https://forthsalon.appspot.com/word-list

NOTE: In Haiku Forth (unlike Traditional Forth), all stack cells and memory locations are floating point numbers.

A Forth Haiku is an attempt to mix mathematics, art, and the Forth programming language. It resembles a texture shader, however, the emphasis is on direct expression in the resulting image.

The Forth program describing each Haiku is run once per pixel over a square image. Forth cells are floating point. Conditions return 1 instead of -1. The position is available from the words x and y, which range from 0 to 1, which the origin in the lower left hand corner. The haiku returns the desired color in (red, green, blue, alpha), with alpha being topmost on the stack. If the stack has less than 4 items default values are assumed: red:0, green:0, blue:0, alpha:1.

Like a traditional haiku, an ideal Forth Haiku has 3 lines of 5, 7, 5 words. Compositions which don't fit the haiku form are either 'short' (less than 140), or 'long'.

Alpha (opacity), can be used to make semi-transparent haiku. Not every haiku will specify alpha (instead relying on the default 1, fully opaque).

Animated Haiku. Some haiku are now animated using the t word to parameterize the haiku by time. The dt is also available to base animation on the time since the last frame. When used in tandem with @ and ! it can be used to make stateful time based haiku.

These haiku can only be seen in animated form using Google Chrome, Firefox, Edge, and Safari.

The haiku is converted on the fly to a GLSL fragment shader.

Language
--------

: ;    Define a new word.

  : <word> <definition...> ;

The complexity surrounding the interpreter state with word definition is glossed over in Haiku Forth. The current implementation works on top of Javascript function definition.

Examples:

    : square ( n -- n ) dup * ; 4 square --> 16

-[ 1]---

x   Put the current x-coordinate on the stack.

  Stack effect: ( -- x )

Unique to Haiku Forth. Returns a floating point number from 0 to 1, where 0 meaning the current pixel is left-most, and 1 means right-most.

-[ 2]---

y   Put the current y-coordinate on the stack.

  Stack effect: ( -- y )

Unique to Haiku Forth. Returns a floating point number from 0 to 1, where 0 meaning the current pixel is bottom-most, and 1 means top-most.

-[ 3]---

t   Put the current time in seconds since midnight on the stack.

  Stack effect: ( -- t )

Unique to Haiku Forth. Returns a floating point number. Intended to avoid run speed dependencies in stateful programs.

-[ 4]---

dt   Put the change in time since the last frame in seconds on the stack.

  Stack effect: ( -- dt )


Unique to Haiku Forth. Returns a floating point number. Midnight based to allow local time clocks.

-[ 5]---

mx   Put the current x-coordinate of the mouse on the stack.

  Stack effect: ( -- x )

Unique to Haiku Forth. Uses the same coordinate space as x.

-[ 6]---

my   Put the current y-coordinate of the mouse on the stack.

  Stack effect: ( -- y )

Unique to Haiku Forth. Uses the same coordinate space as y.

-[ 7]---

button   Put the state of a given button on the stack.

  Stack effect: ( n -- n )

Unique to Haiku Forth. Returns an integer number. There are an unspecified number of buttons. One current implementation provides 23 buttons.

Mouse clicks and single or double touch on touch devices (also mouse + touch) go button 0. Keyboard is also attached at:

  Q:0 W:2 E:4 R:6 T:? Y:?  U:13 I:15 O:17 P:19 [:21
  A:1 S:3 D:5 F:7 G:? H:10 J:14 K:16 L:18 ;:20 ':22
  Z:? X:? C:8 V:9 B:? N:11 M:12

-[ 8]---

buttons  Put the state of several buttons on the stack.

  Stack effect: ( -- n )

Unique to Haiku Forth. Returns an integer number. Each button is represented by 1 bit position in the integer. There are an unspecified number of buttons. One current implementation provides 23 buttons.

Mouse clicks and single or double touch on touch devices (also mouse + touch) go button 0. Keyboard is also attached at:

  Q:0 W:2 E:4 R:6 T:? Y:?  U:13 I:15 O:17 P:19 [:21
  A:1 S:3 D:5 F:7 G:? H:10 J:14 K:16 L:18 ;:20 ':22
  Z:? X:? C:8 V:9 B:? N:11 M:12

-[9]---

@   Read the value at a memory address.

  Stack effect: ( a -- n )

In Haiku Forth, only 16 memory locations 0-15 are provided. Fractional addresses are floored. Out of bounds addresses are wrapped. While accessible from each pixel location, only values stored when x=0, y=0 are persisted to the next frame. NOTE: The memory layout of Haiku Forth may change in the future. Do not rely on wrap around.

-[10]---

!   Store a value to a memory address.

  Stack effect: ( n a -- )

In Haiku Forth, only 16 memory locations 0-15 are provided. Fractional addresses are floored. Out of bounds addresses are wrapped. While accessible from each pixel location, only values stored when x=0,y=0 are persisted to the next frame. NOTE: The memory layout of Haiku Forth may change in the future. Do not rely on wrap around.

-[11]---

(   A comment until the next ")".

  Stack effect: ( -- )

Ignore everything until the next ")".

-[12]---

\   A comment until the end of the line.

  Stack effect: ( -- )

Ignore everything until the end of the line.

-[13]---

>r  (or push) MOVES (not copies) one value from the data stack to the return stack.

Forth uses two stacks, the data stack and the return stack. Most operations occur on the data stack. The return stack can be crucial when reaching below the top two data stack elements, or to put aside values. In traditional Forth, the return stack does double duty, being used to track the return address of the current caller of a word. As such, it is important to balance what you push and pop to the return stack within each scope. The current Haiku Forth implementation does not use the return stack for flow control, however, this behavior may change in future versions.

In tranditional Forth, this word is called >r to visually illustrate how data flows to the return stack. The variant push (from colorForth) is supported as this form is more conducive to cell phone entry.

Examples:

    1 2 3 push + pop * --> 9
    2dup push push * pop pop / - --> (a*b) - (a/b)

-[14]---

r>  (or pop) Moves (not copies) one value from the return stack to the data stack.

Forth uses two stacks, the data stack and the return stack. Most operations occur on the data stack. The return stack can be crucial when reaching below the top two data stack elements, or to put aside values. In traditional Forth, the return stack does, double duty, being used to track the return address of the current caller of a word. As such, it is important to balance what you push and pop to the return stack within each scope. The current Haiku Forth implement does not use the return stack for flow control, however, this behavior may change in future versions.

In tranditional Forth, this word is called r> to visually illustrate how data flows out of the return stack. The variant pop (from colorForth) is supported as this form is more conducive to cell phone entry.

Examples:

    1 2 3 push + pop * --> 9
    2dup push push * pop pop / - --> (a*b) - (a/b)

-[15]---

r@  Copy the top value from the return stack to the data stack.

Forth uses two stacks, the data stack and the return stack. Most operations occur on the data stack. The return stack can be crucial when reaching below the top two data stack elements, or to put aside values. In traditional Forth, the return stack does, double duty, being used to track the return address of the current caller of a word. As such, it is important to balance what you push and pop to the return stack within each scope. The current Haiku Forth implement does not use the return stack for flow control, however, this behavior may change in future versions.

Examples:

    1 2 3 push * r@ + pop + --> 8

-[16]---

dup  Duplicate the element on top of the stack.

  Stack effect: ( n -- n n )

Examples:

    1 2 3 dup --> 1 2 3 3
    4 dup dup --> 4 4 4

-[17]---

over  Duplicate the element under the top stack element.

  Stack effect: ( a b -- a b a )

Examples:

    1 2 3 over --> 1 2 3 2

-[18]----

2dup  Duplicate the top two elements on the stack.

  Stack effect: ( a b -- a b a b )

Examples:

    1 2 3 2dup --> 1 2 3 2 3

-[19]---

drop  Drop the top element from the stack.

  Stack effect: ( n -- )

Examples:

    1 2 3 drop --> 1 2

-[20]---

swap  Swap the top two elements on the stack.

  Stack effect: ( a b -- b a )

Examples:

    1 2 3 swap --> 1 3 2

-[21]---

rot  Rotate the top three elements on the stack [012..]-->[120..]

  Stack effect: ( a b c -- b c a )

Examples:

    1 2 3 rot --> 2 3 1

-[22]---

-rot  Reverse rotate the top three elements on the stack  [012..]-->[201..]

  Stack effect: ( a b c -- c a b )

Examples:

    1 2 3 -rot --> 3 1 2

-[23]---

=   isEqual?

  Stack effect: ( a b -- f )

isEqual? 1 if the top two stack elements are equal, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    1 2 = --> 0
    3 3 = --> 1

-[24]---

<>  isNotEqual?

  Stack effect: ( a b -- f )

isNotEqual? 1 if the top two stack elements are not equal, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    1 2 <> --> 1
    3 3 <> --> 0

-[25]---

<   isLess?

  Stack effect: ( a b -- f )

isLess? 1 if a is less than b, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    1 2 < --> 1
    3 3 < --> 0

-[26]---

>   isGreater?

  Stack effect: ( a b -- f )

isGreater? 1 if a is greater than b, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    2 1 > --> 1
    3 3 > --> 0

-[27]---

<=  isLessEqual?

  Stack effect: ( a b -- f )

isLessEqual? 1 if a is less than or equal to b, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    2 1 <= --> 0
    3 3 <= --> 1

-[28]---

>=  isGreaterEqual?

  Stack effect: ( a b -- f )

isGreaterEqual? 1 if a is greater than or equal to b, else 0.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    1 2 >= --> 0
    3 3 >= --> 1

-[29]---

and  Find the logical "and" of the top two elements on the stack.

  Stack effect: ( f f -- f )

NOTE: In contrast to traditional Forth, logical "and" is used instead of bitwise "and". This choice was made because in a Forth with a floating point data stack, logical operations are more useful in combining multiplicative masks, whereas bitwise operations are at best ambiguous.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    0 0 and --> 0
    0 1 and --> 0
    1 0 and --> 0
    1 1 and --> 1

-[30]---

or  Find the logical "or" of the top two elements on the stack.

  Stack effect: ( f f -- f )

NOTE: In contrast to traditional Forth, logical "or" is used instead of bitwise "or". This choice was made because in a Forth with a floating point data stack, logical operations are more useful in combining multiplicative masks, whereas bitwise operations are at best ambiguous.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    0 0 or --> 0
    0 1 or --> 1
    1 0 or --> 1
    1 1 or --> 1

-[31]---

not  Find the logical "not" of the top two elements on the stack.

  Stack effect: ( f -- f )

Find the logical "not" of the top two elements on the stack.

NOTE: In contrast to traditional Forth, logical "not" is used instead of bitwise INVERT. This choice was made because in a Forth with a floating point data stack, logical operations are more useful in combining multiplicative masks, whereas bitwise operations are at best ambiguous.

Boolean values in Haiku Forth are returned as 1 (true) or 0 (false). This is in contrast to traditional Forth in which -1 is used for true. This choice to go 1 for true was made to facilitate using boolean value as multiplicative masks. For example: x 0.5 < * . The Forth/C convention that anything non-zero is considered an alternate stand-in for true is carried over.

Examples:

    0 not --> 1
    1 not --> 0

-[32]---

min  Select the smaller of the top two stack elements.

  Stack effect: ( n n -- n )

Examples:

    2 3 min --> 2

-[33]---

max  Select the larger of the top two stack elements.

  Stack effect: ( n n -- n )

Select the larger of the top two stack elements.

Examples:

    2 3 max --> 3

-[34]---

+   Add the top two numbers on the stack.

  Stack effect: ( n n -- n )

Examples:

    1 2 + --> 3

-[35]---

-   Subtract the top element on the stack from the next element.

  Stack effect: ( n n -- n )

Subtract the top element on the stack from the next element.

Examples:

    7 4 - --> 3

-[36]---

*  Multiple the top two elements on the stack.

  Stack effect: ( n n -- n )

Examples:

    7 4 * --> 28

-[37]---

/   Divide the second element on the stack by the top element.

  Stack effect: ( n n -- n )

NOTE: As the traditional Forth divide operation uses integers and rounds toward zero, this operation will return different results, even with integer inputs.

Examples:

    8 4 / --> 2
    3 2 / --> 1.5

-[38]---

mod   Find a mod b

  Stack effect: ( n n -- n )

NOTE: As the traditional Forth mod operation uses integers and rounds toward zero, this operation will return different results, even with integer inputs.

Examples:

    9 4 mod --> 1

-[39]---

**  (pow) Find a to the bth power.

  Stack effect: ( n n -- n )

This word is roughly equivalent to the traditional Forth word F**. ** is used to emphasize the primary stack being floating point. Additionally the C derived word pow is supported.

Examples:

    2 3 pow --> 8
    2 3 ** --> 8

-[40]---

atan2  Find the arctangent of a/b.

  Stack effect: ( a b -- n )

This word is roughly equivalent to the traditional Forth word FATAN2. atan2 is used to emphasize the primary stack being floating point.

Examples:

    0 1 atan2 --> 0
    1 0 atan2 --> pi/2

-[41]---

negate  Negate the element on top of the stack (unary minus).

  Stack effect: ( n -- n )

Examples:

    2 negate --> -2
    0 negate --> 0
    -4 negate --> 4

-[42]---

sin  Compute the sine of the top element of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FSIN. sin is used to emphasize the primary stack being floating point.

Examples:

    0 sin --> 0
    pi 2 / sin --> 1

-[43]---

cos  Compute the cosine of the top element of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FCOS. cos is used to emphasize the primary stack being floating point.

Examples:

    0 cos --> 1
    pi 2 / cos --> 0

-[44]---

tan   Compute the tangent the top element of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FTAN. tan is used to emphasize the primary stack being floating point.

Examples:

    0 tan --> 0

-[45]---

log   Compute the log base e of the top element of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FLN. log is used to emphasize the primary stack being floating point, with a slight nod to the C function name.

Examples:

    1 log --> 0

-[46]---

exp  Compute e raised to the power on top of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FEXP. exp is used to emphasize the primary stack being floating point.

Examples:

    0 exp --> 1

-[47]---

sqrt   Compute the square root of the top element on the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FSQRT. sqrt is used to emphasize the primary stack being floating point.

Examples:

    4 sqrt --> 2

-[48]---

floor  Round the number on top of the stack downward.

  Stack effect: ( n -- n )

Examples:

    1.234 floor --> 1

-[49]---

ceil  Round the number on top of the stack upward.

  Stack effect: ( n -- n )

Not in traditional Forth, included for completeness, borrowing the C function name.

Examples:

    1.234 ceil --> 2

-[50]---

abs  Compute the absolute value of the number on top of the stack.

  Stack effect: ( n -- n )

This word is roughly equivalent to the traditional Forth word FABS. abs is used to emphasize the primary stack being floating point.

Examples:

    -123 abs --> 123
    -1.2 abs --> 1.2

-[51]---

pi  Push pi onto the stack.

  Stack effect: ( -- n )

This word is Haiku Forth specific, included for completeness.

Examples:

    pi --> 3.1415926535897931

-[52]---

z+   Complex addition.

  Stack effect: ( a b c d -- a+c b+d )

Haiku Forth specific word nominally to add two complex numbers on the stack. It could be used to add a two vector as well, as which part it real or imaginary does not matter for this operation.

Examples:

    1 11 5 9 z+ --> 6 20

-[53]---

z*   Complex multiplication.

  Stack effect: ( a b c d -- a*c-b*d a*d+b*c )

Haiku Forth specific word to multiple two complex numbers on the stack. Complex number are expected to be stored on the stack with the real part deeper in the stack (corresponding to real part first when pushing constants onto the stack.

Examples:

    1 11 5 9 z* --> -94 64
    2dup z* --> complex square

-[54]---

random  Return a pseudo-random number in the range [0, 1).

  Stack effect: ( -- n )

This word is Haiku Forth specific.

-[55]---

if else then   Conditional statements.

if <true> else <false> then

if <true> then

Pops a value from the stack, if non-zero execute the true case. Otherwise execute the false case if any. In Haiku Forth, the data-stack and return-stack depth in both cases of the conditional must remain the same.

Examples:

    1 .5 > if 3 else 4 then --> 3
    3 1 .5 > if 1 + then --> 4
