I need some way to simulate class behaviour in q
Something I can call like this
d: .dictBuilder.new[];d.put[
y;13];d.put[h
jk; ("a";"b";"c")];res: d.build[];show resx| 1y| 13h| "a"j| "b"k| "c"
So I came up with this idea
- store class instance in a namespace dict and keyed by instance id. new dict entry will be added every time new is called
For example, dict3 and dict4 are two instances created in memory
show .dictBuildermax_instance_id | 4dict3 | ``y!(();13)dict4 | ``h
jk!(();"a";"b";"c")
-
use function projection with instance id to simulate method call on instance (note projection with
dict3])
.dictBuilder.put: {[instance_id;k;v] $[0 > type k; .dictBuilder[instance_id],:(enlist k)! enlist v; .dictBuilder[instance_id],:(k)! v]; };.dictBuilder.build: {[instance_id; dummy] r: .dictBuilder[instance_id]; .dictBuilder: instance_id _ .dictBuilder; //remove instance after it was built r:_ r; //remove null key r};
-
instance id is generated and bind to instance method at creation
.dictBuilder.new:{ if[not
dictBuilder in key ; .dictBuilder.max_instance_id: -1]; //create new namespace if not exist instance_id:
$“d”,string .dictBuilder.max_instance_id+:1; //assign new instance id .dictBuilder[instance_id]: (enlist)!enlist(); //create new instance builder: (enlist
)!enlist(); builder[instance_id]: instance_id; builder[
put]: .dictBuilder.put[instance_id]; builder[build]: .dictBuilder.build[instance_id]; builder};
- done. you can call it like above code
Does anyone have other solution for this? Are you aware of any problem with this approach?
The reason why I came up with this idea is simply because I was looking for a cleaner way to do this
To create generic dict, this wouldn’t work
d: ()!();d[
x]: 1;d[`y]: “f”`type`
So I had to do this.
d: (enlist
)!enlist();d[x]: 1;d[
y]: “f”; _ d