A little concordance

Summary

Richard Suchenwirth 2002-05-13: Reading "An Overview of the Icon programming language" [L1 ], their final example of a concordance (index of words, with linenumber where it occurred) challenged me to redo it in Tcl. Easily done, of course - now to see how Icon features might be borrowed for Tcl...

Description

set test {
      On the Future!-how it tells
      Of the rapture that impells
     To the swinging and the ringing
      Of the bells, bells, bells-
   Of the bells, bells, bells, bells, 
             Bells, bells, bells-
To the rhyming and the chiming of the bells!
}

proc concordance {text} {
    set n 0
    foreach line [split $text \n] {
        if {$line==""} continue
        regsub -all {[^a-z]} [string tolower $line] " " line2
        incr n
        foreach word $line2 {
            if [string length $word]>=3 {lappend A($word) $n}
        }
        puts [format "%10d %s" $n $line]
    }
    puts ""
    foreach word [lsort [array names A]] {
        puts [format "%-15s %s" $word [join [luniq $A($word)] ", "]]
    }
}
proc luniq list {
    set res {}
    foreach i $list {
        if {[lsearch $res $i]<0} {lappend res $i}
    }
    set res
}

concordance $test
        1        On the Future!-how it tells
        2        Of the rapture that impells
        3       To the swinging and the ringing
        4        Of the bells, bells, bells-
        5     Of the bells, bells, bells, bells, 
        6               Bells, bells, bells-
        7  To the rhyming and the chiming of the bells!

and             3, 7
bells           4, 5, 6, 7
chiming         7
future          1
how             1
impells         2
rapture         2
rhyming         7
ringing         3
swinging        3
tells           1
that            2
the             1, 2, 3, 4, 5, 7