Reverse words in a string: Difference between revisions
Content added Content deleted
Line 1,125: | Line 1,125: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
The word "parse-name" consumes a word from input stream and places it on the stack. The word "type" takes a word from the data stack and prints it. Calling these two words before and after the recursive call effectively reverses a string. |
|||
The method shown is based on submissions in comp.lang.forth. Comments have been added for those less familiar with reading Forth. This example makes use of the Forth interpreter/compiler internals by calling PARSE-NAME which is a Forth 2012 word that parses the input stream, ignores leading spaces and delimits at the space character. This method makes clever use of the data stack. Strings are not copied in memory by rather pointers are collected on the stack as PARSE-NAME processes a sentence. This of course leaves the strings in the reversed order so they are simply printed off the data stack. |
|||
<lang>: not-empty? dup 0 > ; |
|||
<lang>create buf 1000 chars allot \ string buffer |
|||
: (reverse) parse-name not-empty? IF recurse THEN type space ; |
|||
buf value pp \ pp points to buffer address |
|||
⚫ | |||
: tr ( caddr u -- ) |
|||
dup >r pp swap cmove \ move string into buffer |
|||
r> pp + to pp ; \ advance pointer by u bytes |
|||
: collect ( -- addr len .. addr[n] len[n]) \ words deposit on data stack |
|||
begin |
|||
parse-name dup \ parse input stream, dup the len |
|||
while \ while stack <> 0 |
|||
tuck pp >r tr r> swap |
|||
repeat |
|||
2drop ; \ clean up stack |
|||
⚫ | |||
buf to pp \ initialize pointer to buffer address |
|||
collect |
|||
depth 2/ 0 ?do type space loop \ type the strings with a trailing space |
|||
cr ; \ final new line |
|||
reverse ---------- Ice and Fire ------------ |
reverse ---------- Ice and Fire ------------ |
||
Line 1,160: | Line 1,143: | ||
'''Output''' |
'''Output''' |
||
Interpreted above code at the Forth console |
Interpreted above code at the Forth console |
||
<pre> |
|||
⚫ | |||
------------ Fire and Ice ---------- |
|||
⚫ | |||
Some say in ice. |
Some say in ice. |
||
From what I've tasted of desire |
From what I've tasted of desire |