Menu
Home
Create new Paste
Log in
Code
Theme: cobalt
Theme: eclipse
Theme: elegant
Theme: monokai
Theme: neat
Theme: night
Theme: rubyblue
module test; import std.stdio; import std.traits; import std.typecons; import std.datetime; enum Rehash { no, yes } template isClassStruct(alias fun) { enum bool isClassStruct = (is(fun == class) || is(fun == struct)); } mixin template memoize(alias fun, uint maxSize = uint.max) if (isClassStruct!(__traits(parent, fun))) { ReturnType!fun[Tuple!(ParameterTypeTuple!fun)] memo; void rehash() { memo = null; } ReturnType!fun opCall(ParameterTypeTuple!fun args) { auto t = tuple(args); auto p = t in memo; if (p) return *p; static if (maxSize != uint.max) { if (memo.length >= maxSize) memo = null; } mixin("auto r = this." ~ __traits(identifier, fun) ~ "(args);"); memo[t] = r; return r; } } class A { int field; int slowFunc(int a, int b) { int result; foreach (_; 0 .. 1024) { result += a; result += b; } return result + field; } mixin memoize!slowFunc fastFunc; } enum CallCount = 2048; void main() { A a = new A; int z = a.fastFunc(100, 100); writeln(z); a.field = 50; a.fastFunc.rehash(); z = a.fastFunc(100, 100); writeln(z); }
Result:
Success
/
Return code: 0
/
Compilation time:
1.316
seconds
/
Run time:
0.023
seconds
Application output:
204800
204850
Username
Message
Add comment
Paste info
Author:
Guest
Views:
128
Private:
no
Expires:
Never
Uploaded:
01.10.12 22:22
Votes
:
0
Tweet
Compilation
Compiler:
DMD 2.060
Pointer size:
m32
Actions
Download
Fork
Raw
×
Confirm
Are you sure you want to delete this paste?
There's no way back!
×
Confirm
Reason