thisExePath purity
Marc Schütz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Sep 20 02:14:39 PDT 2016
On Tuesday, 20 September 2016 at 04:17:21 UTC, crimaniak wrote:
> Hi and thanks all!
>
> On Tuesday, 20 September 2016 at 00:43:10 UTC, Jonathan M Davis
> wrote:
>
>> immutable string executablePath;
>>
>> shared static this()
>> {
>> import std.file : thisExePath();
>> executablePath = thisExePath();
>> }
>
> This code is good for my needs but I start to think about how
> to call thisExePath only if it is really used and come to this
> solution:
>
> import std.traits: ReturnType, Parameters;
>
> string staticMemoize(alias T, Parms = Parameters!T)() pure
> {
> struct Holder(alias T)
> {
> static shared immutable ReturnType!T value;
> shared static this(){ value = T(Parms); }
> }
>
> return Holder!T.value;
> }
>
> unittest
> {
> import std.file : thisExePath;
> assert(staticMemoize!thisExePath == thisExePath);
> }
>
> Something like this. Need to refine about input parameters, but
> I hope, idea is clear.
> Unlike the function memoize from phobos staticMemoize really
> pure. And unlike proposed solution with ordinary variable
> staticMemoize is lazy, because no call - no instantiation.
Have a look at `std.concurrency.initOnce`:
https://dlang.org/phobos/std_concurrency.html#.initOnce
But you will still need to use assumePure() for calling
`thisExePath`, and it might do other things that are impure...
More information about the Digitalmars-d-learn
mailing list