The easiest part is to update the implementation of the readFile() function, by replacing push() with extend() :

fun readFile () { val f = read ( stack . pop () as String ) stack . extend ( f ) (1) }

1 At this point, the stack should consist of one element per line of text in the read file

The next step requires to pop every string from the stack, process it, then to push it back. However, because of the nature of the stack, the processed string will be put back on top. And only the top string can be accessed. We could use the heap instead of pushing back the string on the stack, but that would be cheating…​

An alternative that is fully stack-compliant is the following:

Push a mutable list on the stack Repeat the following until there’s but one element on the stack Swap the two first elements - the list and the string Pop the first element - that would be the string to process Process the string Pop the now first element - that would be the list Add the processed string to the list Push back the list onto the stack Finally, pop the list that contains all processed strings And push its contents as individual strings on the stack

There’s one additional trick. To add an element to a mutable list, the API is list.add(string) . On the stack, this would translate as stack.pop().add(stack.pop()) . That means the list should be the first item on the stack. However, the order in our process is reversed: the first item should be the string, the second one the list. Hence, we need a function that reverse the order of the caller - the list - and of the callee - the string. This is easily done with another extension function:

fun < T > T . addTo ( collection : MutableCollection < T >) = collection . also { it . add ( this ) }

The associated implementation is:

fun filterChars () { stack . push ( mutableListOf < String >()) while ( stack . size > 1 ) { stack . swap () stack . push ( "\\W|_" . toRegex () . replace (( stack . pop () as String ), " " ) . toLowerCase () . addTo ( stack . pop () as MutableList < Any >) ) } stack . extend ( stack . pop () as MutableList < Any >) }