BagInterface
BeginPackage["BagInterface`"];
ExprBag::usage= "Top-level interface to Bag";
BeginPackage["`Package`"];
ConstructExprBag::usage="";
ExprBagQ::usage="";
BagAppendTo::usage="";BagLength::usage="";BagPart::usage="";
BagSetPart::usage="";BagMap::usage="";BagCopy::usage="";BagToList::usage="";BagExtend::usage="";BagTake::usage="";
EndPackage[];
Begin["`Private`"];
⌈Object⌋
ExprBag//Clear
⌈BagQ⌋
ExprBagQ//Clear
ExprBagQ[e_ExprBag?System`Private`HoldNoEntryQ]:=True;ExprBagQ[e_]:=False
⌈Constructor⌋
ExprBag[bag_Internal`Bag]?System`Private`HoldEntryQ:= ConstructExprBag[bag];ExprBag[e_List]:= With{res=ConstructExprBag[e]}, res/;ExprBagQ[res] ;ExprBag[]:= ConstructExprBag@Internal`Bag[];
ConstructExprBag[bag_Internal`Bag]:= System`Private`HoldSetNoEntry[ExprBag[bag]];ConstructExprBag[e_List]:= ConstructExprBag@Internal`Bag[e]
⌈Format⌋
⌈Package Functions⌋
⌈BagAppendTo⌋
⌈BagLength⌋
⌈BagPart⌋
⌈BagSetPart⌋
⌈BagCopy⌋
⌈BagMap⌋
⌈BagToList⌋
⌈BagExtend⌋
⌈BagTake⌋
⌈Overrides⌋
⌈UpValues⌋
ExprBag/:Length[e_ExprBag?ExprBagQ]:= BagLength[e];ExprBag/:Normal[e_ExprBag?ExprBagQ]:= BagToList[e];ExprBag/:Part[e_ExprBag?ExprBagQ,i_]:= BagPart[e,i];ExprBag/:Take[e_ExprBag?ExprBagQ,s_]:= BagTake[e,s];
ExprBag/:Internal`BagPart[ExprBag[bag_Internal`Bag]?ExprBagQ,b_]:= Internal`BagPart[bag,b];ExprBag/:Internal`BagLength[ExprBag[bag_Internal`Bag]?ExprBagQ]:= Internal`BagLength[bag]ExprBag/:Internal`StuffBag[ExprBag[bag_Internal`Bag]?ExprBagQ,b_]:= Internal`StuffBag[bag,b];
⌈Methods⌋
ExprBag/:e_ExprBag?ExprBagQ["Map"[f_]]:= BagMap[f];ExprBag/:e_ExprBag?ExprBagQ["Copy"[]]:= BagCopy[];ExprBag/:e_ExprBag?ExprBagQ["Extend"[iterable_]]:= BagCopy[];ExprBag/:(ExprBag[bag_]?ExprBagQ)["Bag"]:=bag
⌈Mutations⌋
bagSymQ[s_]:= MatchQ[OwnValues[s],{__ExprBag?ExprBagQ}];bagSymQ~SetAttributes~HoldFirst;
BagMutationHandler//ClearAllBagMutationHandler~SetAttributes~HoldAllComplete;BagMutationHandler[(Set|SetDelayed)[Part[s:_ExprBag?ExprBagQ|_Symbol?bagSymQ,p_],v_]]:= BagSetPart[s,p,v];BagMutationHandler[AppendTo[s:_ExprBag?ExprBagQ|_Symbol?bagSymQ,v_]]:= BagAppendTo[s,v];BagMutationHandler[___]:= Language`MutationFallthroughLanguage`SetMutationHandler[ExprBag,BagMutationHandler];
End[];
EndPackage[];
In[]:=
<<BagInterface`
In[]:=
eb=ExprBag[];Length@eb
Out[]=
0
In[]:=
AppendTo[eb,1];//RepeatedTiming
Out[]=
{0.000011,Null}
In[]:=
Length@eb
Out[]=
5655
In[]:=
b=ExprBag@Take[eb,UpTo[25]];
In[]:=
Take[b,UpTo[26]]//Length
Out[]=
25
In[]:=
b[[5]]=5
Out[]=
5
In[]:=
Normal@b
Out[]=
{1,1,1,1,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
In[]:=
testBag=ExprBag@Range[100000];
In[]:=
AppendTo[testBag,1];//RepeatedTiming
Out[]=
{0.0000107,Null}
In[]:=
lll=Range[100000];
In[]:=
AppendTo[lll,1];//RepeatedTiming
Out[]=
{0.0001,Null}
In[]:=
testBag["Bag"]
Out[]=
Internal`Bag[<105530>]
In[]:=
lll//Length
Out[]=
105420