Skip to content

Commit 541dae8

Browse files
Update triadicmemory.m
Add a general expression encoder/decoder
1 parent 78c51d8 commit 541dae8

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

Mathematica/triadicmemory.m

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,39 @@ and associated documentation files (the “Software”), to deal in the Software
4848
f[x_SparseArray, y_SparseArray, z_SparseArray] := (++W[[##]] & @@@ tup[x, y, z];);
4949

5050
(* recall x, y, or z *)
51-
f[_, y_SparseArray, z_SparseArray] := f[ Plus @@ ( W[[All, #1, #2]] & @@@ tup[y, z])];
52-
f[x_SparseArray, _, z_SparseArray] := f[ Plus @@ ( W[[#1, All, #2]] & @@@ tup[x, z])];
53-
f[x_SparseArray, y_SparseArray, _] := f[ Plus @@ ( W[[#1, #2, All]] & @@@ tup[x, y])];
51+
f[Verbatim[_], y_SparseArray, z_SparseArray] := f[ Plus @@ ( W[[All, #1, #2]] & @@@ tup[y, z])];
52+
f[x_SparseArray, Verbatim[_], z_SparseArray] := f[ Plus @@ ( W[[#1, All, #2]] & @@@ tup[x, z])];
53+
f[x_SparseArray, y_SparseArray, Verbatim[_]] := f[ Plus @@ ( W[[#1, #2, All]] & @@@ tup[x, y])];
5454

5555
];
5656

5757

58+
59+
(* Wrapper for TriadicMemory which automatically encodes any Mathematica expression to random sparse arrays *)
60+
61+
62+
TriadicMemoryEncoding[f_Symbol, {n_Integer, p_Integer} ] :=
63+
64+
Module[ {T, encode, decode, pos},
65+
66+
TriadicMemory[ T, {n, p}];
67+
68+
pos[x_SparseArray] := Sort[Flatten[x["NonzeroPositions"]]];
69+
70+
encode[x_SparseArray] := x;
71+
encode[Verbatim[_]] = _;
72+
encode[Null] = SparseArray[{0}, {n}];
73+
encode[s_] :=
74+
encode[s] = Module[ {r = T[]}, decode[pos[r]] = s; r];
75+
76+
decode[SparseArray[{0}, {n}]] = Null;
77+
decode[x_SparseArray] := Module[ {r}, r = decode[ pos[x]]; If[ Head[r] === decode, x, r]];
78+
decode[Null] = Null;
79+
80+
f[] = T[]; (* random generator *)
81+
82+
f[x_, y_, z_] := decode[ T[ encode[x], encode[y], encode[z]]];
83+
84+
];
85+
86+

0 commit comments

Comments
 (0)