root/trunk/samples/wc.md

Revision 292, 1.6 kB (checked in by JarrettBillingsley, 7 months ago)

Closes #65. Also fixed a bug in the regexp.email predefined regexp, and a small bug in dumpVal.

Line 
1 module wc
2
3 function main()
4 {
5     local w_total = 0
6     local l_total = 0
7     local c_total = 0
8     local dictionary = {}
9    
10     if(#vararg == 0)
11         return
12    
13     writefln("   lines   words   bytes  file")
14    
15     for(iarg: 0 .. #vararg)
16     {
17         local arg = vararg[iarg]
18    
19         local w_cnt = 0
20         local l_cnt = 0
21         local inword = false
22    
23         local c_cnt = io.size(arg)
24    
25         local f = io.readFile(arg)
26         local wstart = 0
27    
28         foreach(j, c; f)
29         {
30             if(c == '\n')
31                 ++l_cnt
32    
33             if(c.isDigit())
34             {
35                 //if(inword)
36                 //  buf ~= c
37             }
38             else if(c.isAlpha() || c == '\'')
39             {
40                 if(!inword)
41                 {
42                     wstart = j
43                     inword = true
44                     w_cnt++
45                 }
46                 else
47                     {}//buf ~= c
48             }
49             else if(inword)
50             {
51                 local word = f[wstart .. j].toLower();
52                 local val = dictionary[word]
53    
54                 if(val is null)
55                     dictionary[word] = 1
56                 else
57                     dictionary[word] += 1
58    
59                 inword = false
60             }
61         }
62    
63         if(inword)
64         {
65             local word = f[wstart .. j].toLower();
66             local val = dictionary[word]
67    
68             if(val is null)
69                 dictionary[word] = 1
70             else
71                 dictionary[word] += 1
72         }
73    
74         writefln("{,8}{,8}{,8}  {}\n", l_cnt, w_cnt, c_cnt, arg)
75         l_total += l_cnt
76         w_total += w_cnt
77         c_total += c_cnt
78     }
79    
80     if(#vararg > 1)
81         writefln("--------------------------------------\n{,8}{,8}{,8}  total", l_total, w_total, c_total)
82    
83     writefln("--------------------------------------")
84    
85     local results = dictionary.keys().apply(function(v) = [v, dictionary[v]]).sort(function(a, b) = b[1] <=> a[1])
86    
87     foreach(word; results)
88         writefln("{,5} {}", word[1], word[0])
89 }
Note: See TracBrowser for help on using the browser.