forked from dlang/dlang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash-map.dd
289 lines (234 loc) · 8.06 KB
/
hash-map.dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
Ddoc
$(SPEC_S Associative Arrays,
$(P Associative arrays have an index that is not necessarily an integer,
and can be sparsely populated. The index for an associative array
is called the $(I key), and its type is called the $(I KeyType).
)
$(P Associative arrays are declared by placing the $(I KeyType)
within the [ ] of an array declaration:
)
---------
int[string] b; // associative array b of ints that are
// indexed by an array of characters.
// The $(CODE_HIGHLIGHT KeyType) is string
b["hello"] = 3; // set value associated with key "hello" to 3
func(b["hello"]); // pass 3 as parameter to func()
---------
$(P Particular keys in an associative array can be removed with the
remove function:
)
---------
b.$(CODE_HIGHLIGHT remove)("hello");
---------
$(P The $(I InExpression) yields a pointer to the value
if the key is in the associative array, or $(D null) if not:
)
---------
int* p;
p = ("hello" $(CODE_HIGHLIGHT in) b);
if (p !is (B null))
...
---------
$(P $(I KeyType)s cannot be functions or voids.
)
$(P The element types of an associative array cannot be functions or voids.)
$(H3 Using Classes as the KeyType)
$(P Classes can be used as the $(I KeyType). For this to work,
the class definition must override the following member functions
of class $(D Object):)
$(UL
$(LI $(D hash_t toHash()))
$(LI $(D bool opEquals(Object)))
$(LI $(D int opCmp(Object)))
)
$(P $(D hash_t) is an alias to an integral type.)
$(P Note that the parameter to $(D opCmp) and $(D opEquals) is
of type
$(D Object), not the type of the class in which it is defined.)
$(P For example:)
---
class Foo {
int a, b;
hash_t $(CODE_HIGHLIGHT toHash)() { return a + b; }
bool $(CODE_HIGHLIGHT opEquals)(Object o)
{ Foo foo = cast(Foo) o;
return foo && a == foo.a && b == foo.b;
}
int $(CODE_HIGHLIGHT opCmp)(Object o)
{ Foo foo = cast(Foo) o;
if (!foo)
return -1;
if (a == foo.a)
return b - foo.b;
return a - foo.a;
}
}
---
$(P The implementation may use either $(D opEquals) or $(D opCmp) or
both. Care should be taken so that the results of
$(D opEquals) and $(D opCmp) are consistent with each other when
the class objects are the same or not.)
$(H3 Using Structs or Unions as the KeyType)
$(P If the $(I KeyType) is a struct or union type,
a default mechanism is used
to compute the hash and comparisons of it based on the binary
data within the struct value. A custom mechanism can be used
by providing the following functions as struct members:
)
---------
const hash_t $(CODE_HIGHLIGHT opHash)();
const bool $(CODE_HIGHLIGHT opEquals)(ref const KeyType s);
const int $(CODE_HIGHLIGHT opCmp)(ref const KeyType s);
---------
$(P For example:)
---------
import std.string;
struct MyString {
string str;
const hash_t $(CODE_HIGHLIGHT toHash)()
{ hash_t hash;
foreach (char c; str)
hash = (hash * 9) + c;
return hash;
}
const bool $(CODE_HIGHLIGHT opEquals)(ref const MyString s)
{
return std.string.cmp(this.str, s.str) == 0;
}
const int $(CODE_HIGHLIGHT opCmp)(ref const MyString s)
{
return std.string.cmp(this.str, s.str);
}
}
---------
$(P The implementation may use either $(D opEquals) or $(D opCmp) or
both. Care should be taken so that the results of
$(D opEquals) and $(D opCmp) are consistent with each other when
the struct/union objects are the same or not.)
$(H3 Runtime Initialization of Immutable AAs)
$(P Immutable associative arrays are often desirable, but sometimes
initialization must be done at runtime. This can be achieved with
a constructor (static constructor depending on scope),
a buffer associative array and $(D assumeUnique):)
---------
immutable long[string] aa;
static this()
{
import std.exception : assumeUnique;
import std.conv : to;
long[string] temp; // mutable buffer
foreach(i; 0 .. 10)
{
temp[to!string(i)] = i;
}
temp.rehash; // for faster lookups
aa = assumeUnique(temp);
}
unittest
{
assert(aa["1"] == 1);
assert(aa["5"] == 5);
assert(aa["9"] == 9);
}
---------
$(H3 Properties)
Properties for associative arrays are:
$(TABLE_2COLS Associative Array Properties,
$(THEAD Property, Description)
$(TROW $(D .sizeof), Returns the size of the reference to the associative
array; it is 4 in 32-bit builds and 8 on 64-bit builds.)
$(TROW $(D .length), $(ARGS Returns number of values in the
associative array. Unlike for dynamic arrays, it is read-only.))
$(TROW $(D .dup), Create a new associative array of the same size
and copy the contents of the associative array into it.)
$(TROW $(D .keys), $(ARGS Returns dynamic array, the elements of which are the keys in
the associative array.))
$(TROW $(D .values), $(ARGS Returns dynamic array, the elements of which are the values in
the associative array.))
$(TROW $(D .rehash), $(ARGS Reorganizes the associative array in place so that lookups
are more efficient. $(D rehash) is effective when, for example,
the program is done loading up a symbol table and now needs
fast lookups in it. Returns a reference to the reorganized array.))
$(TROW $(D .byKey()), $(ARGS Returns a delegate suitable for use as an $(I Aggregate) to
a $(GLINK2 statement, ForeachStatement) which will iterate over the keys
of the associative array.))
$(TROW $(D .byValue()), $(ARGS Returns a delegate suitable for use as an $(I Aggregate) to
a $(GLINK2 statement, ForeachStatement) which will iterate over the values
of the associative array.))
$(TROW $(D .get(Key key, lazy Value defVal)),
$(ARGS Looks up $(D key); if it exists returns corresponding value
else evaluates and returns $(D defVal).))
)
$(HR)
$(H3 Associative Array Example: word count)
$(P Let's consider the file is ASCII encoded with LF EOL.
In general case we should use $(I dchar c) for iteration
over code points and functions from $(LINK2 phobos/std_uni.html,std.uni).
)
---------
import std.file; // D file I/O
import std.stdio;
import std.ascii;
void main (string[] args) {
ulong totalWords, totalLines, totalChars;
ulong[string] dictionary;
writefln(" lines words bytes file");
foreach (arg; args[1 .. $]) // for each argument except the first one
{
ulong wordCount, lineCount, charCount;
foreach(line; File(arg).byLine())
{
bool inWord;
size_t wordStart;
void tryFinishWord(size_t wordEnd)
{
if (inWord)
{
auto word = line[wordStart .. wordEnd];
++dictionary[word.idup]; // increment count for word
inWord = false;
}
}
foreach (i, char c; line)
{
if (std.ascii.isDigit(c))
{ // c is a digit (0..9)
}
else if (std.ascii.isAlpha(c))
{ // c is an ASCII letter (A..Z, a..z)
if (!inWord)
{
wordStart = i;
inWord = true;
++wordCount;
}
}
else
tryFinishWord(i);
++charCount;
}
tryFinishWord(line.length);
++lineCount;
}
writefln("%8s%8s%8s %s", lineCount, wordCount, charCount, arg);
totalWords += wordCount;
totalLines += lineCount;
totalChars += charCount;
}
if (args.length > 2)
{
writefln("-------------------------------------\n%8s%8s%8s total",
totalLines, totalWords, totalChars);
}
writeln("-------------------------------------");
foreach (word; dictionary.keys.sort)
{
writefln("%3s %s", dictionary[word], word);
}
}
---------
)
Macros:
TITLE=Associative Arrays
WIKI=AssociativeArrays
CATEGORY_SPEC=$0