I do not believe it is possible to use InitializationValue
for a set-delayed value. I found this out when I tried to use the resource function "PersistResourceFunction"
and found that it would load the definitions at kernel start time which is in my opinion unacceptable, and saw that it was implemented using InitializationValue
.
Why not just do it the old fashioned way? Put something like this in your kernel init.m
file
UnsortedComplement := (
ClearAll[UnsortedComplement];
UnsortedComplement[args__] := code here;
(* protect it if you like *)
UnsortedComplement
)
Or wrap it up in a package and use the paclet manager's autoloading mechanism, which I very much prefer over InitializationValue
.
I actually only discovered "PersistResourceFunction"
because my own submission "UseResourceFunctionAsSymbol"
was rejected as a duplicate. My version of the function creates a local paclet called ResourceFunctionSymbols
and will add resource functions to that paclet when you call it.
(* add a resource function to the list and then quit the kernel *)
UseResourceFunctionAsSymbol["UnsortedComplement"];
Quit[]
Now you always have the symbol UnsortedComplement
available at kernel startup, without the overhead of InitializationValue
:
In[1]:= OwnValues[UnsortedComplement] // Short
Out[1]//Short= {HoldPattern[UnsortedComplement]:>Package`ActivateLoad[<<1>>]}
In[2]:= UnsortedComplement[{4, 4, 4, 4, 3, 3, 3, 2, 2, 1}, {3, 2}]
Out[2]= {4, 4, 4, 4, 1}
UseResourceFunctionAsSymbol
is defined below.
setDefinitions[names_, context_] := ToExpression[
Map[StringJoin[context, #]&, names],
StandardForm,
Function[Null,
With[{sn = SymbolName @ Unevaluated @ #},
# := # = ResourceFunction[sn, "Function"] (* ignore the syntax highlighting here, the FE is wrong *)
],
HoldAllComplete
]
];
UseResourceFunctionAsSymbol[function_String, Optional[context_String, "Global`"]] := Module[
{
functions,
pacletDir = FileNameJoin @ {$UserBasePacletsDirectory, "Repository", "ResourceFunctionSymbols"}
},
If[
FailureQ[Quiet @ ResourceFunction @ function],
Return[$Failed, Module]
];
functions = Replace[ResourceFunctionSymbols`Private`$installedResources, Except[_ ? ListQ] :> {}];
Quiet @ PacletManager`PacletUninstall @ "ResourceFunctionSymbols";
If[DirectoryQ[pacletDir],
DeleteDirectory[pacletDir, DeleteContents -> True]
];
AppendTo[functions, function];
ResourceFunctionSymbols`Private`$installedResources = functions;
setDefinitions[functions, context];
functions = Append[functions, "$installedResources"];
Block[{$ContextPath = Join[$ContextPath, {"ResourceFunctionSymbols`Private`"}]},
ResourceFunction["Pacletize"]["ResourceFunctionSymbols", functions, FileNameDrop @ pacletDir]
];
Symbol @ function
]