\ twigs.txt Leo Wong 26 March 02003 fyj + \ Count occurrences of words in a file: after K&R, 2nd ed, p. 140-142 \ Usage example at the end of this file include from.txt from tools.txt from string.txt from bintree.txt from files.txt \ Each twig has: left pointer, right pointer, count, word : Left ( node -- a ) ; immediate : Right ( node -- a ) CELL+ ; : >Count ( node -- a ) >data ; : >Word ( node -- a ) >Count CELL+ ; \ New Twig if new word, else up count : New-Twig ( a u node -- ) link 1 , string, ; DEFER comp ' COMPARE IS comp : ?Twig ( a u tree -- ) DUP @ 0= IF New-Twig EXIT THEN @ DUP >R >Word COUNT 2OVER comp ?DUP 0= IF R> >Count ++ 2DROP EXIT THEN 0< IF R> Right ELSE R> Left THEN RECURSE ; \ Display a word and its count : .Twig ( node -- ) CR DUP >Word COUNT TYPE SPACE >Count ? ; ' .Twig IS xnode : Grow-Tree ( a u tree -- ) >R BEGIN DUP WHILE word> R@ ?Twig REPEAT 2DROP R> DROP ; : xFile ( tree -- ) >R 0 PARSE open-in BEGIN readl WHILE R@ Grow-Tree REPEAT 2DROP close-in R> DROP ; bintree Top \ Usage: Twigs : Twigs ( -- ) HERE Top 0 OVER ! DUP xFile xbintree HERE - ALLOT ; Twigs Twigs.txt