Sort three variables: Difference between revisions

Line 452:
(from the 'Wizard of OZ'),bears, oh my!,lions, tigers, and
</pre>
 
=={{header|Forth}}==
==={{header|Integers}}===
In GNU Forth the machine's integers are the default data type.
It is straightforward to sort these on the Forth Data Stack
<LANG>\ sort 3 integers
 
: ?SWAP ( a b -- a b) \ conditional swap
2DUP < IF SWAP THEN ;
 
: SORT3INTS ( a b c -- c b a) ?SWAP >R ?SWAP R> ?SWAP ;
 
</LANG>
Testing is done using the Forth console using '.S' to view the Data stack contents.
<pre> ok
1 2 3 ok
.S <3> 1 2 3 ok
SORT3INTS ok
.S <3> 3 2 1 ok
</PRE>
==={{header|Strings}}===
Strings require extending language but the primitives needed are part of ANS/ISO Forth.
<LANG>DECIMAL
: BUFFER: ( n -- ) CREATE ALLOT ;
 
64 BUFFER: X
64 BUFFER: Y
64 BUFFER: Z
 
: S' ( <text> ) [CHAR] ' PARSE ;
 
S' (from the "Wizard of OZ")' X PLACE
S' bears, oh my!' Y PLACE
S' lions, tigers, and' Z PLACE
 
\ string less than
: <S ( caddr caddr -- caddr caddr)
2DUP COUNT ROT COUNT COMPARE 1 = ;
 
: ?SWAPSTR ( caddr caddr -- caddr caddr) \ conditional strin swap
<S IF SWAP THEN ;
 
\ sort on stack as done for integers
: SORT3STRINGS ?SWAPSTR >R ?SWAPSTR R> ?SWAPSTR ;
 
: .STR ( caddr1 caddr2 caddr3 -- )
3 0 DO DUP CR COUNT TYPE ROT LOOP ;
</LANG>
With these extensions we can do the same testing at the Forth console and
examine the string order with '.STR'.
<PRE>ok
X Y Z ok
.STR
lions, tigers, and
(from the "Wizard of OZ")
bears, oh my! ok
ok
SORT3STRINGS ok
.STR
(from the "Wizard of OZ")
lions, tigers, and
bears, oh my! ok
</PRE>
 
 
=={{header|Fortran}}==
Anonymous user