11-conditionals.fth 809 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. \ -1: true
  2. \ 0: false
  3. \ Read further for more info.
  4. \ Conditionals can only be used inside colon definitions.
  5. : abs ( n1 -- +n2 )
  6. dup 0 < if negate endif ;
  7. \ `if` looks at the topmost cell on the stack. If it
  8. \ contains a non-zero value, it is interpreted as truthy. If
  9. \ it is zero, it is interpreted as falsy. Usually -1 is used
  10. \ for true.
  11. \ `endif` is equivalent to `then`. The tutorial gives the
  12. \ following definition for endif:
  13. ( : endif postpone then ; immediate )
  14. : abs ( n1 -- +n2 )
  15. dup 0 < if negate then ;
  16. \ There is also an if-else-then:
  17. : min ( n1 n2 -- n )
  18. 2dup < if drop else nip then ;
  19. 2 3 min .
  20. 3 2 min .
  21. \ Exercise: min without using an else branch.
  22. : min ( n1 n2 -- n )
  23. \ Only let the `if` decide whether or not to swap the
  24. \ arguments.
  25. 2dup > if swap then
  26. drop ;