History variables: Difference between revisions

no edit summary
m (→‎Version 1: added comments, changed indentation and comments. -- ~~~~)
No edit summary
Line 259:
 
<pre>foobar <- foo <- 5
</pre>
 
=={{header|D}}==
D does not have history variables. The following implementation provides a generic HistoryVariable that protects the historical values by defining them as 'immutable'.
 
<lang d>import std.stdio;
import std.array;
import std.string;
import std.datetime;
import std.traits;
 
/* A value in a point in time */
struct HistoryValue(T)
{
SysTime time;
T value;
 
void toString(scope void delegate(const(char)[]) 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);
}
 
T currentValue() const pure nothrow @property
{
return values.back.value;
}
 
alias this = currentValue;
 
auto history() const pure nothrow @property
{
return values;
}
 
/* Demonstrating D's compile-time reflection features. The member
* functions that are in this 'static if' block would be added for
* variables that are of array types (including strings). */
static if (isArray!T) {
 
// Append-with-assign operator
void opOpAssign(string op : "~")(T element)
{
auto newValue = currentValue ~ element;
addValue(newValue);
}
 
// ... similar implementation for other array operators ...
}
}
 
void test(T : int)()
{
auto variable = HistoryVariable!int();
 
variable = 1;
variable = 2;
variable = 3;
 
writefln("%(%s\n%)", variable.history);
}
 
void test(T : string)()
{
auto s = HistoryVariable!string();
 
s = "hello";
s ~= " world";
s = "goodby";
 
writefln("%(%s\n%)", s.history);
}
 
void main()
{
test!int();
test!string();
}
</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
2013-Jan-19 23:04:55.1662596; goodby
</pre>
 
Anonymous user