Frequency Table
### Frequency Table
### prints sorted frequency table for a sequence
function freqcount(seq)
## create map of counters
local m := {};
## for each word in text that matches pattern
for word in seq
m[word] := m[word] + 1;
end;
## sort list of Map Entries by their values
sort((a, b) -> b.value - a.value, append([], m));
end;
txt:= "If in this heart a hope be dear,
That sound shall charm it forth again:
If in these eyes there lurk a tear,
'Twill flow, and cease to burn my brain";
wordlist := map(f"lowercase", append([], re_seq(r"\w+", txt)));
wordfreq := freqcount(wordlist);
print(i"Word frequency table for text
$(txt)
$(wordfreq)\n\n");
charfreq := freqcount(txt);
print (i"Character frequency table for text
$(txt)
$(charfreq)\n\n");
## make array of random integers
numbers := map( x -> random(10), make_array(size:=20));
numbersfreq := freqcount( numbers );
print (i"Frequency table for array of numbers
$(numbers)
$(numbersfreq)\n\n");
Output:
Word frequency table for text
If in this heart a hope be dear,
That sound shall charm it forth again:
If in these eyes there lurk a tear,
'Twill flow, and cease to burn my brain
[if=2, a=2, in=2, be=1, sound=1, hope=1, eyes=1, these=1, that=1, tear=1, and=1, dear=1, twill=1, flow=1, burn=1, again=1, this=1, shall=1, it=1, forth=1, my=1, brain=1, heart=1, lurk=1, cease=1, charm=1, there=1, to=1]
Character frequency table for text
If in this heart a hope be dear,
That sound shall charm it forth again:
If in these eyes there lurk a tear,
'Twill flow, and cease to burn my brain
[ =48, a=13, e=13, h=9, r=9, t=9, i=7, n=7, l=6, s=6, o=5, f=4,
=3, b=3, d=3, ,=3, u=3, I=2, T=2, =2, c=2, m=2, w=2, y=2, g=1, '=1, k=1, p=1, :=1]
Frequency table for array of numbers
[6, 3, 6, 7, 7, 0, 0, 2, 5, 9, 7, 7, 5, 9, 7, 2, 2, 0, 2, 4]
[7=5, 2=4, 0=3, 5=2, 6=2, 9=2, 3=1, 4=1]