History variables: Difference between revisions

m
m (Corrected a typo.)
imported>Arakov
 
(2 intermediate revisions by 2 users not shown)
Line 522:
{{out}}
<pre>foobar <- foo <- 5
</pre>
 
=={{header|C++}}==
C++ does not have history variables, but they can easily by implemented with a generic class.
<syntaxhighlight lang="c++">
#include <deque>
#include <iostream>
#include <string>
 
template <typename T>
class with_history {
public:
with_history(const T& element) {
history.push_front(element);
}
 
T get() {
return history.front();
}
 
void set(const T& element) {
history.push_front(element);
}
 
std::deque<T> get_history() {
return std::deque<T>(history);
}
 
T rollback() {
if ( history.size() > 1 ) {
history.pop_front();
}
return history.front();
}
 
private:
std::deque<T> history;
};
 
int main() {
with_history<double> number(1.2345);
std::cout << "Current value of number: " << number.get() << std::endl;
 
number.set(3.4567);
number.set(5.6789);
 
std::cout << "Historical values of number: ";
for ( const double& value : number.get_history() ) {
std::cout << value << " ";
}
std::cout << std::endl << std::endl;
 
with_history<std::string> word("Goodbye");
word.set("Farewell");
word.set("Hello");
 
std::cout << word.get() << std::endl;
word.rollback();
std::cout << word.get() << std::endl;
word.rollback();
std::cout << word.get() << std::endl;
word.rollback();
std::cout << word.get() << std::endl;
word.rollback();
}
</syntaxhighlight>
{{ out }}
<pre>
Current value of number: 1.2345
Historical values of number: 5.6789 3.4567 1.2345
 
Hello
Farewell
Goodbye
Goodbye
</pre>
 
Line 817 ⟶ 892:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import extensions;
import system'collections;
Line 869 ⟶ 944:
console.printLine(o);
o.forEach:(printingLn);
o.undo().undo().undo();
Line 2,939 ⟶ 3,014:
{{trans|Kotlin}}
Not built in but we can soon make a suitable class.
<syntaxhighlight lang="ecmascriptwren">class HistoryVariable {
construct new(initValue) {
_history = [initValue]
Anonymous user