Synopsis Counting words in strings.
Examples The purpose of WordCount is to count the number of words in a list of lines (strings). A word is here defined as one or more letters (lowercase or uppercase), digits and the underscore character (_).

We split the problem in two parts:
  • Count the words in a single line. We explore three ways to do this in an imperative (CountInLine1, CountInLine2) and a functional style (CountInLine3).
  • Next we apply the single line counter to all the lines.
wordCount is a function with two arguments:
  • A list of lines.
  • A function that returns the number of words in a line.
The main task of wordCount is to loop over all lines and to add the word counts per line.

module demo::common::WordCount::WordCount

// wordCount takes a list of strings and a count function
// that is applied to each line. The total number of words is returned

public int wordCount(list[str] input, int (str s) countInLine)
  count = 0;
  for(str line <- input){           
     count += countInLine(line);    
  return count;
At an Rascal:Enumerator is used to generated all the lines in the list of lines. At the argument function countInLine is applied to count the number of words in each line.

Let's now do some experiments using the Jabberwocky poem by Lewis Carrol as input. Explain what is going on in this function.
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit