\ Split, a Forth program to split a integer (up to 999999999) into seperate digits. by T.Porter 2016 \ Written on FreeBSD using Mecrisp-Stellaris Forth (http://mecrisp.sourceforge.net/) running on a STM32F0 Discovery board, communicating via a Forth Express serial terminal by kfoltman. \ : split >R BEGIN R> ?DUP 0 > WHILE 10 /MOD >R . cr REPEAT ; \ Split program explained : split >R \ Save the input on the Return Stack BEGIN R> ?DUP 0 > WHILE \ Fetch from the Return Stack, duplicate because " 0 >" and "/MOD" both use it, then continue while greater than zero after dividing by 10. ?DUP is used instead of DUP to prevent a zero being left on the stack after the program has completed. 10 /MOD >R . cr \ divide by 10 and save the result on the Return Stack, print each remainder on a new line REPEAT ; \ Anything added to the return stack during the execution of a word must be removed before the word ends, and the same is true for a loop. So the Return Stack must be tested for 'balance'. \ In this variation of split, print a label for every Return Stack ADD and REMOVE to visually compare them : split-labels >R ." " cr \ 999999999 maximum input BEGIN R> ." " cr ?DUP 0 > WHILE 10 /MOD >R ." " cr . REPEAT ; \ This time every Return Stack ADD is worth 1 and REMOVE is worth -1. A total of 0 shows the Return Stack is balanced, so no visual comparison is required. 0 variable rb \ : split-rbalance >R rb @ 1+ rb ! BEGIN R> rb @ 1- rb ! ?DUP 0 > WHILE 10 /MOD >R rb @ 1+ rb ! . cr REPEAT ." R balance = " rb @ . ; \ *************************** screen pics of all three variants ;) ********************** \ Forth> 123456789 split \ -> 123456789 split \ <- 9 \ <- 8 \ <- 7 \ <- 6 \ <- 5 \ <- 4 \ <- 3 \ <- 2 \ <- 1 \ <- ok. \ Forth> 123456789 split-labels \ -> 123456789 split-labels \ <- \ <- \ <- \ <- 9 \ <- \ <- 8 \ <- \ <- 7 \ <- \ <- 6 \ <- \ <- 5 \ <- \ <- 4 \ <- \ <- 3 \ <- \ <- 2 \ <- \ <- 1 \ <- ok. \ Forth> 123456789 split-rbalance \ -> 123456789 split-rbalance \ <- 9 \ <- 8 \ <- 7 \ <- 6 \ <- 5 \ <- 4 \ <- 3 \ <- 2 \ <- 1 \ <- R balance = 0 ok. \ \ \ **************************************************************************