forked from DlangRen/Programming-in-D
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parameter_flexibility.d
520 lines (387 loc) · 13.9 KB
/
parameter_flexibility.d
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
Ddoc
$(DERS_BOLUMU $(IX parameter, variable number of) Variable Number of Parameters)
$(P
This chapter covers two D features that bring flexibility on parameters when calling functions:
)
$(UL
$(LI Default arguments)
$(LI Variadic functions)
)
$(H5 $(IX default argument) $(IX argument, default) Default arguments)
$(P
A convenience with function parameters is the ability to specify default values for them. This is similar to the default initial values of struct members.
)
$(P
Some of the parameters of some functions are called mostly by the same values. To see an example of this, let's consider a function that prints the elements of an associative array of type $(C string[string]). Let's assume that the function takes the separator characters as parameters as well:
)
---
import std.algorithm;
// ...
void printAA(in char[] title,
in string[string] aa,
in char[] keySeparator,
in char[] elementSeparator) {
writeln("-- ", title, " --");
auto keys = sort(aa.keys);
foreach (i, key; keys) {
// No separator before the first element
if (i != 0) {
write(elementSeparator);
}
write(key, keySeparator, aa[key]);
}
writeln();
}
---
$(P
That function is being called below by $(STRING ":") as the key separator and $(STRING ", ") as the element separator:
)
---
string[string] dictionary = [
"blue":"mavi", "red":"kırmızı", "gray":"gri" ];
printAA("Color Dictionary", dictionary, ":", ", ");
---
$(P
The output:
)
$(SHELL
-- Color Dictionary --
blue:mavi, gray:gri, red:kırmızı
)
$(P
If the separators are almost always going to be those two, they can be defined with default values:
)
---
void printAA(in char[] title,
in string[string] aa,
in char[] keySeparator $(HILITE = ": "),
in char[] elementSeparator $(HILITE = ", ")) {
// ...
}
---
$(P
Parameters with default values need not be specified when the function is called:
)
---
printAA("Color Dictionary",
dictionary); /* ← No separator specified. Both
* parameters will get their
* default values. */
---
$(P
The parameter values can still be specified when needed, and not necessarily all of them:
)
---
printAA("Color Dictionary", dictionary$(HILITE , "="));
---
$(P
The output:
)
$(SHELL
-- Color Dictionary --
blue=mavi, gray=gri, red=kırmızı
)
$(P
The following call specifies both of the parameters:
)
---
printAA("Color Dictionary", dictionary$(HILITE , "=", "\n"));
---
$(P
The output:
)
$(SHELL
-- Color Dictionary --
blue=mavi
gray=gri
red=kırmızı
)
$(P
Default values can only be defined for the parameters that are at the end of the parameter list.
)
$(H6 Special keywords as default arguments)
$(P
$(IX special keyword) $(IX keyword, special) The following special keywords act like compile-time literals having values corresponding to where they appear in code:
)
$(UL
$(LI $(IX __MODULE__) $(C __MODULE__): Name of the module)
$(LI $(IX __FILE__) $(C __FILE__): Name of the source file)
$(LI $(IX __LINE__) $(C __LINE__): Line number)
$(LI $(IX __FUNCTION__) $(C __FUNCTION__): Name of the function)
$(LI $(IX __PRETTY_FUNCTION__) $(C __PRETTY_FUNCTION__): Full signature of the function)
)
$(P
Although they can be useful anywhere in code, they work differently when used as default arguments. When they are used in regular code, their values refer to where they appear in code:
)
---
import std.stdio;
void func(int parameter) {
writefln("Inside function %s at file %s, line %s.",
__FUNCTION__, __FILE__, __LINE__); $(CODE_NOTE $(HILITE line 5))
}
void main() {
func(42);
}
---
$(P
The reported line 5 is inside the function:
)
$(SHELL
Inside function deneme.$(HILITE func) at file deneme.d, $(HILITE line 5).
)
$(P
However, sometimes it is more interesting to determine the line where a function is called from, not where the definition of the function is. When these special keywords are provided as default arguments, their values refer to where the function is called from:
)
---
import std.stdio;
void func(int parameter,
string functionName = $(HILITE __FUNCTION__),
string file = $(HILITE __FILE__),
size_t line = $(HILITE __LINE__)) {
writefln("Called from function %s at file %s, line %s.",
functionName, file, line);
}
void main() {
func(42); $(CODE_NOTE $(HILITE line 12))
}
---
$(P
This time the special keywords refer to $(C main()), the caller of the function:
)
$(SHELL
Called from function deneme.$(HILITE main) at file deneme.d, $(HILITE line 12).
)
$(P
$(IX special token) $(IX token, special) In addition to the above, there are also the following $(I special tokens) that take values depending on the compiler and the time of day:
)
$(UL
$(LI $(IX __DATE__) $(C __DATE__): Date of compilation)
$(LI $(IX __TIME__) $(C __TIME__): Time of compilation)
$(LI $(IX __TIMESTAMP__) $(C __TIMESTAMP__): Date and time of compilation)
$(LI $(IX __VENDOR__) $(C __VENDOR__): Compiler vendor (e.g. $(STRING "Digital Mars D")))
$(LI $(IX __VERSION__) $(C __VERSION__): Compiler version as an integer (e.g. the value $(C 2069) for version 2.069))
)
$(H5 $(IX variadic function) Variadic functions)
$(P
Despite appearances, default parameter values do not change the number of parameters that a function receives. For example, even though some parameters may be assigned their default values, $(C printAA()) always takes four parameters and uses them according to its implementation.
)
$(P
On the other hand, variadic functions can be called with unspecified number of arguments. We have already been taking advantage of this feature with functions like $(C writeln()). $(C writeln()) can be called with any number of arguments:
)
---
writeln(
"hello", 7, "world", 9.8 /*, and any number of other
* arguments as needed */);
---
$(P
There are four ways of defining variadic functions in D:
)
$(UL
$(LI $(IX _argptr) The feature that works only for functions that are marked as $(C extern(C)). This feature defines the hidden $(C _argptr) variable that is used for accessing the parameters. This book does not cover this feature partly because it is unsafe.)
$(LI $(IX _arguments) The feature that works with regular D functions, which also uses the hidden $(C _argptr) variable, as well as the $(C _arguments) variable, the latter being of type $(C TypeInfo[]). This book does not cover this feature as well both because it relies on $(I pointers), which have not been covered yet, and because this feature can be used in unsafe ways as well.)
$(LI A safe feature with the limitation that the unspecified number of parameters must all be of the same type. This is the feature that is covered in this section.)
$(LI Unspecified number of template parameters. This feature will be explained later in the templates chapters.)
)
$(P
$(IX ..., function parameter) The parameters of variadic functions are passed to the function as a slice. Variadic functions are defined with a single parameter of a specific type of slice followed immediately by the $(C ...) characters:
)
---
double sum(in double[] numbers$(HILITE ...)) {
double result = 0.0;
foreach (number; numbers) {
result += number;
}
return result;
}
---
$(P
That definition makes $(C sum()) a variadic function, meaning that it is able to receive any number of arguments as long as they are $(C double) or any other type that can implicitly be convertible to $(C double):
)
---
writeln(sum($(HILITE 1.1, 2.2, 3.3)));
---
$(P
The single slice parameter and the $(C ...) characters represent all of the arguments. For example, the slice would have five elements if the function were called with five $(C double) values.
)
$(P
In fact, the variable number of parameters can also be passed as a single slice:
)
---
writeln(sum($(HILITE [) 1.1, 2.2, 3.3 $(HILITE ]))); // same as above
---
$(P
Variadic functions can also have required parameters, which must be defined first in the parameter list. For example, the following function prints an unspecified number of parameters within parentheses. Although the function leaves the number of the elements flexible, it requires that the parentheses are always specified:
)
---
char[] parenthesize(
in char[] opening, // ← The first two parameters must be
in char[] closing, // specified when the function is called
in char[][] words...) { // ← Need not be specified
char[] result;
foreach (word; words) {
result ~= opening;
result ~= word;
result ~= closing;
}
return result;
}
---
$(P
The first two parameters are mandatory:
)
---
parenthesize("{"); $(DERLEME_HATASI)
---
$(P
As long as the mandatory parameters are specified, the rest are optional:
)
---
writeln(parenthesize("{", "}", "apple", "pear", "banana"));
---
$(P
The output:
)
$(SHELL
{apple}{pear}{banana}
)
$(H6 Variadic function arguments have a short lifetime)
$(P
The slice argument that is automatically generated for a variadic parameter points at a temporary array that has a short lifetime. This fact does not matter if the function uses the arguments only during its execution. However, it would be a bug if the function kept a slice to those elements for later use:
)
---
int[] numbersForLaterUse;
void foo(int[] numbers...) {
numbersForLaterUse = numbers; $(CODE_NOTE_WRONG BUG)
}
struct S {
string[] namesForLaterUse;
void foo(string[] names...) {
namesForLaterUse = names; $(CODE_NOTE_WRONG BUG)
}
}
void bar() {
foo(1, 10, 100); /* The temporary array [ 1, 10, 100 ] is
* not valid beyond this point. */
auto s = S();
s.foo("hello", "world"); /* The temporary array
* [ "hello", "world" ] is not
* valid beyond this point. */
// ...
}
void main() {
bar();
}
---
$(P
Both the free-standing function $(C foo()) and the member function $(C S.foo()) are in error because they store slices to automatically-generated temporary arrays that live on the program stack. Those arrays are valid only during the execution of the variadic functions.
)
$(P
For that reason, if a function needs to store a slice to the elements of a variadic parameter, it must first take a copy of those elements:
)
---
void foo(int[] numbers...) {
numbersForLaterUse = numbers$(HILITE .dup); $(CODE_NOTE correct)
}
// ...
void foo(string[] names...) {
namesForLaterUse = names$(HILITE .dup); $(CODE_NOTE correct)
}
---
$(P
However, since variadic functions can also be called with slices of proper arrays, copying the elements would be unnecessary in those cases.
)
$(P
A solution that is both correct and efficient is to define two functions having the same name, one taking a variadic parameter and the other taking a proper slice. If the caller passes variable number of arguments, then the variadic version of the function is called; and if the caller passes a proper slice, then the version that takes a proper slice is called:
)
---
int[] numbersForLaterUse;
void foo(int[] numbers$(HILITE ...)) {
/* Since this is the variadic version of foo(), we must
* first take a copy of the elements before storing a
* slice to them. */
numbersForLaterUse = numbers$(HILITE .dup);
}
void foo(int[] numbers) {
/* Since this is the non-variadic version of foo(), we can
* store the slice as is. */
numbersForLaterUse = numbers;
}
struct S {
string[] namesForLaterUse;
void foo(string[] names$(HILITE ...)) {
/* Since this is the variadic version of S.foo(), we
* must first take a copy of the elements before
* storing a slice to them. */
namesForLaterUse = names$(HILITE .dup);
}
void foo(string[] names) {
/* Since this is the non-variadic version of S.foo(),
* we can store the slice as is. */
namesForLaterUse = names;
}
}
void bar() {
// This call is dispatched to the variadic function.
foo(1, 10, 100);
// This call is dispatched to the proper slice function.
foo($(HILITE [) 2, 20, 200 $(HILITE ]));
auto s = S();
// This call is dispatched to the variadic function.
s.foo("hello", "world");
// This call is dispatched to the proper slice function.
s.foo($(HILITE [) "hi", "moon" $(HILITE ]));
// ...
}
void main() {
bar();
}
---
$(P
Defining multiple functions with the same name but with different parameters is called $(I function overloading), which is the subject of the next chapter.
)
$(PROBLEM_TEK
$(P
Assume that the following $(C enum) is already defined:
)
---
enum Operation { add, subtract, multiply, divide }
---
$(P
Also assume that there is a $(C struct) that represents the calculation of an operation and its two operands:
)
---
struct Calculation {
Operation op;
double first;
double second;
}
---
$(P
For example, the object $(C Calculation(Operation.divide, 7.7, 8.8)) would represent the division of 7.7 by 8.8.
)
$(P
Design a function that receives an unspecified number of these $(C struct) objects, calculates the result of each $(C Calculation), and then returns all of the results as a slice of type $(C double[]).
)
$(P
For example, it should be possible to call the function as in the following code:
)
---
void $(CODE_DONT_TEST)main() {
writeln(
calculate(Calculation(Operation.add, 1.1, 2.2),
Calculation(Operation.subtract, 3.3, 4.4),
Calculation(Operation.multiply, 5.5, 6.6),
Calculation(Operation.divide, 7.7, 8.8)));
}
---
$(P
The output of the code should be similar to the following:
)
$(SHELL
[3.3, -1.1, 36.3, 0.875]
)
)
Macros:
SUBTITLE=Variable Number of Parameters
DESCRIPTION=Default values for function parameters; and the 'variadic function' feature that allows passing variable number of arguments to functions.
KEYWORDS=d programming book tutorial struct