Anonymous user
History variables: Difference between revisions
Formatting and small changes in D entry
(Formatting and small changes in D entry) |
|||
Line 262:
=={{header|D}}==
D does not have history variables. The following implementation provides a generic HistoryVariable that protects the historical values by defining them as '
<lang d>import std.stdio, std.array, std.string, std.datetime, std.traits;
/* A value in a point in time */▼
struct
static struct HistoryValue {
// Alternative to the more common toString.
void toString(scope void delegate(const(char)[]) output) const▼
//void toString(scope void delegate(string) output) const {
{▼
output(format("%s; %s", time, value));
}
}
▲/* A history variable */
struct HistoryVariable(T)▼
▲ immutable(HistoryValue!T)[] values;
private void addValue(T value) {
▲ {
▲ values ~= cast(immutable)HistoryValue!T(Clock.currTime, value);
}
void opAssign(T value) {
addValue(value);
}
@property T currentValue() const pure nothrow
return values.back.value;
}
Line 304 ⟶ 296:
alias this = currentValue;
@property auto history() const pure nothrow
return values;
}
types T that are arrays (including strings). */
static if (isArray!T) {
// Append-with-assign operator.▼
void opOpAssign(string op : "~")(T element) {
▲ // Append-with-assign operator
▲ {
}
//
}
}
void
auto variable = HistoryVariable!int();▼
▲ variable = 2;
▲ variable = 3;
▲ writefln("%(%s\n%)", variable.history);
s = "hello";
s ~= " world";
s = "goodby";
writefln("%(%s\n%)", s.history);
}</lang>▼
▲</lang>
▲'''Sample Output'''
<pre>2013-Jan-19 23:04:55.1660302; 1
2013-Jan-19 23:04:55.1660407; 2
2013-Jan-19 23:04:55.1660424; 3
2013-Jan-19 23:04:55.1662551; hello
2013-Jan-19 23:04:55.1662581; hello world
|