Word count (Rexx)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Assembly Intel x86 Linux | C | C++ | Haskell | J | Lua | OCaml | Perl | Python, functional | Rexx

This program counts the number of characters, words, and lines in the file supplied on standard input and writes the counts to standard output.

The common idiom for processing a stream of data in Rexx is to read lines repeatedly in a loop until there are no more left. This loop uses the Rexx Signal instruction to create an end-of-file handler (the "not ready" condition) that will exit the loop.

<<main loop>>=
Signal on NotReady label EndOfFile
Do Forever
   Parse pull Line
   process one line

For this counting program, the work to be performed on each line is to count the line, the words in it, and the characters in it. To do so, we start by setting up three counters and initialize them:

<<initialize variables>>=
LineCount = 0
WordCount = 0
CharCount = 0

and then we increment them accordingly when processing an input line:

<<process one line>>=
   LineCount = LineCount + 1
   WordCount = WordCount + Words(Line)
   CharCount = CharCount + Length(Line)

Pulling it all together and writing the results out, we have a functioning program:

/* Word counter in Rexx.  Writes counts of lines, words and characters to standard output */
initialize variables

main loop

Say LineCount WordCount CharCount

[edit] Counting words in a string

This example above takes advantage of the Rexx Words() built-in function, however that function is relatively simple to implement in Rexx as well, albeit with less efficiency than the built-in version.

The word counting loop uses the Rexx Parse instruction to strip one word off the beginning of the string repeatedly until the line is entirely consumed, counting the words as it goes:

<<Words loop>>=
Do N = 0 by 1 While Line <> ""
   Parse var Line . Line

Add in a little boilerplate to make a function out of the loop, and we have an alternative to the built-in:

Words: Procedure
Line = Arg(1)
Words loop
Return N
Download code