Key value coding and observing is something that other languages do well, like objective-c for instance. What's the best way to achieve something similar in Mathematica (if at all possible)? That is, how can you trigger an event based on a certain variable's value changing without relying on front-end dynamics...
1 Answer
Here's a simplistic way to do what I needed, that is, running some code before and after the variable updates:
ClearAll[kvo, r];
SetAttributes[kvo, {HoldAll}];
kvo[v_, pre_, post_] := ((v /: Set[v, x_] := (pre[v]; v := x; post[x])))
kvo[r, Print["before update, var = ", #] &,
Print["after update, var = ", #, "\n"] &]
Do[r = i^2, {i, 3}]
outputs
before update, var = r
after update, var = 1
before update, var = 1
after update, var = 4
before update, var = 4
after update, var = 9
Thanks @leonid for the link, very helpful, but that solution is a bit overkill for my needs....
CompoundExpression
in your programs, but, say,AngleBracket
and do something likeUnprotect[AngleBracket]; Precedence[AngleBracket] = 10.; SetAttributes[AngleBracket, HoldAll];
and then defineAngleBracket[expr1_, expr2_, expri___]
in such a way that after each evaluation of an argument a list ofKVO
pure function triggers would be checked. You could also add quite effective debugging this way I guess. Sorry to not work this out more, but time is short these days ... $\endgroup$