Saturday, May 28, 2011

LIB2: Tutorial, part 1

As work continues on LIB2 more samples are moved to it. So it's time to take a look at the changes the new library brought with it

#symbol Program =>
'program'Output << "Hello World!!%n".

'program'input get. // wait for any key

As you can see little was changes: a generic message GET is used instead of CHAR'GET. So let's look at more complex sample: words

#define std'basic'*.
#define std'collections'*.
#define std'patterns'*.
#define ext'text'*.
#define ext'patterns'*.
#define ext'routines'*.

#subject std'dictionary'*.

#subject total_words, unique_words.

// --- WordList ---

#class WordList
#field theList.
#field theTotal.

#method new
theList := List.
theTotal := Integer::0.

#method += aWord
theTotal += 1.

#if (ListSearching::theList ==aWord)?
| [ theList += aWord literal. ].

#method total_words = theTotal.

#method unique_words = theList count.

#annex (theList).

// --- Program ---

#symbol Program =>
'program'output << "Enter the text(to stop press enter two times):%n".

#var aFlag := Boolean << True.
#var aText := TextWriter.
#var aWriter := #annex(aText)
<< aLiteral
#if (aLiteral length == 0)?
aFlag << False.
| [ aText << aLiteral. ].

#loop aFlag?
'program'Input >> aWriter.

aWriter += " ".

#var aList := WordList.

WordScan::aText run: aWord => (aList += aWord).

'program'output << "There are " << aList unique_words << " unique words out of " << aList total_words.
'program'output << "%nthe list of unique words:%n".

aList~CollectionPrinter save:'program'output.

'program'input get. // wait for any key

The first thing that catch an eye is a possibility to use symbol names without a namespace qualifier or an alias. New modules (like ext'routines) and classes (ext'text'TextWriter) were introduced. ext'patterns'WordEnum was renamed to WordScan. An external role ext'routines'CollectionPrinter is used to print the collection. Qualified messages unique_words and total_words are used instead of private ones $getTotal and $getUnique. Apart from these the sample logic remains the same: with the help of wordscan the entered text is split into words and only unique words are saved in the collection; the resulting list is printed at the end.

No comments:

Post a Comment