How do I get the value cache()?

Adam D. Ruppe destructionator at gmail.com
Mon Jan 15 03:28:09 UTC 2018


On Monday, 15 January 2018 at 02:54:16 UTC, Marc wrote:
> let's assume I have
>
>> class C {
>>   static string foo() { writeln("got called!"); //.... }
>> }
>
> then I want to cache foo at some point:
>
>> import std.algorithm;
>> auto v = cache(c.foo);

That doesn't do what I think you think it does.

http://dpldocs.info/experimental-docs/std.algorithm.iteration.cache.html

Notice it is from the `iteration` module.. the cache function 
caches results of an iteration, not results of a function. It 
actually returns an object that caches the individual characters 
of that string, rather than the string!

The memoize function is closer to what you want:
http://dpldocs.info/experimental-docs/std.functional.memoize.2.html


Though tbh, I think you should just simply do:

string s = c.foo;
// go ahead and just use s now


> here's why I'm confused more often than I should: I geeeting to 
> D's way to do thing and the auto keyword even in documentation 
> confused me a bit as I'm used to C++/C# world where the 
> struct/class returned is explicity so I just navigate to 
> aggregate type's documentation page.

The tricky thing is a lot of them create a new type based on its 
arguments, so there would be nothing to navigate to - it all 
depends on what you pass it.

Though, you'll notice with memoize, it returns `ReturnType!fun`, 
that is, the same return type fun (which you passed to it) had.


More information about the Digitalmars-d-learn mailing list