Caching expressions
I find these functions very helpful to cache any expression. The interesting thing here for these two functions is that the held expression itself is used as a key of the hashtable/symbol Cache or CacheIndex, compared to the well-known memoization in mathematica where you can only cache result if the function is defined like f[x_] := f[x] = ... So you can cache any part of a code, this is useful if a function is to be called several times but just some parts of the code must not be recomputed.
To cache an expression independently of its arguments.
SetAttributes[Cache, HoldFirst];
c:Cache[expr_] := c = expr;
Ex: Cache[Pause[5]; 6]
Cache[Pause[5]; 6]
The second time the expression returns 6 without waiting.
To cache an expression using an alias expression that can depend on an argument of the cached expression.
SetAttributes[CacheIndex, HoldRest];
c:CacheIndex[index_,expr_] := c = expr;
Ex: CacheIndex[{"f",2},x=2;y=4;x+y]
If expr takes some time to compute, it is much faster to evaluate {"f",2} for example to retrieve the cached result.
For a variation of these functions in order to have a localized cache (ie. the cache memory is automatically released outside the Block construct) see this post Avoid repeated calls to Interpolation
Deleting cached values
To delete cached values when you don't know the number of definitions of a function. I consider that definitions have a Blank somewhere in their arguments.
DeleteCachedValues[f_] :=
DownValues[f] = Select[DownValues[f], !FreeQ[Hold@#,Pattern]&];
To delete cached values when you know the number of definitions of a function (goes slightly faster).
DeleteCachedValues[f_,nrules_] :=
DownValues[f] = Extract[DownValues[f], List /@ Range[-nrules, -1]];
This uses the fact that definitions of a function are at the end of their DownValues list, cached values are before.
Using symbols to store data and object-like functions
Also here are interesting functions to use symbols like objects.
It is already well known that you can store data in symbols and quickly access them using DownValues
mysymbol["property"]=2;
You can access the list of keys (or properties) of a symbol using these functions based on what dreeves submitted in a post on this site:
SetAttributes[RemoveHead, {HoldAll}];
RemoveHead[h_[args___]] := {args};
NKeys[symbol_] := RemoveHead @@@ DownValues[symbol(*,Sort->False*)][[All,1]];
Keys[symbol_] := NKeys[symbol] /. {x_} :> x;
I use this function a lot to display all infos contained in the DownValues of a symbol:
PrintSymbol[symbol_] :=
Module[{symbolKeys},
symbolKeys = Keys[symbol];
TableForm@Transpose[{symbolKeys, symbol /@ symbolKeys}]
];
Finally here is a simple way to create a symbol that behaves like an object in object oriented programming (it just reproduces the most basic behaviour of OOP but I find the syntax elegant) :
Options[NewObject]={y->2};
NewObject[OptionsPattern[]]:=
Module[{newObject},
newObject["y"]=OptionValue[y];
function[newObject,x_] ^:= newObject["y"]+x;
newObject /: newObject.function2[x_] := 2 newObject["y"]+x;
newObject
];
Properties are stored as DownValues and methods as delayed Upvalues in the symbol created by Module that is returned. I found the syntax for function2 that is the usual OO-syntax for functions in Tree data structure in Mathematica.
For a list of existing types of values each symbol has, see http://reference.wolfram.com/mathematica/tutorial/PatternsAndTransformationRules.html and http://www.verbeia.com/mathematica/tips/HTMLLinks/Tricks_Misc_4.html.
For example try this
x = NewObject[y -> 3];
function[x, 4]
x.function2[5]
You can go further if you want to emulate object inheritance using a package called InheritRules available here
http://library.wolfram.com/infocenter/MathSource/671/
You could also store the function definition not in newObject but in a type symbol, so if NewObject returned type[newObject] instead of newObject you could define function and function2 like this
outside of NewObject (and not inside) and have the same usage as before.
function[type[object_], x_] ^:= object["y"] + x;
type /: type[object_].function2[x_] := 2 object["y"]+x;
Use UpValues[type] to see that function and function2 are defined in the type symbol.
Further ideas about this last syntax are introduced here https://mathematica.stackexchange.com/a/999/66.
Improved version of SelectEquivalents
@rcollyer: Many thanks for bringing SelectEquivalents to the surface, it's an amazing function.
Here is an improved version of SelectEquivalents listed above with more possibilities and using options, this makes it easier to use.
Options[SelectEquivalents] =
{
TagElement->Identity,
TransformElement->Identity,
TransformResults->(#2&) (*#1=tag,#2 list of elements corresponding to tag*),
MapLevel->1,
TagPattern->_,
FinalFunction->Identity
};
SelectEquivalents[x_List,OptionsPattern[]] :=
With[
{
tagElement=OptionValue@TagElement,
transformElement=OptionValue@TransformElement,
transformResults=OptionValue@TransformResults,
mapLevel=OptionValue@MapLevel,
tagPattern=OptionValue@TagPattern,
finalFunction=OptionValue@FinalFunction
}
,
finalFunction[
Reap[
Map[
Sow[
transformElement@#
,
{tagElement@#}
]&
,
x
,
{mapLevel}
]
,
tagPattern
,
transformResults
][[2]]
]
];
Here are examples of how this version can be used:
Using Mathematica Gather/Collect properly
How would you do a PivotTable function in Mathematica?
Mathematica fast 2D binning algorithm
Internal`Bag
Daniel Lichtblau describes here an interesting internal data structure for growing lists.
Implementing a Quadtree in Mathematica
Debugging functions
These two posts point to useful functions for debugging:
How to debug when writting small or big codes using Mathematica? workbench? mma debugger? or something else? (ShowIt)
https://stackoverflow.com/questions/5459735/the-clearest-way-to-represent-mathematicas-evaluation-sequence/5527117#5527117 (TraceView)
Here's another function based on Reap and Sow to extract expressions from different parts of a program and store them in a symbol.
SetAttributes[ReapTags,HoldFirst];
ReapTags[expr_]:=
Module[{elements},
Reap[expr,_,(elements[#1]=#2/.{x_}:>x)&];
elements
];
Here's an example
ftest[]:=((*some code*)Sow[1,"x"];(*some code*)Sow[2,"x"];(*some code*)Sow[3,"y"]);
s=ReapTags[ftest[]];
Keys[s]
s["x"]
PrintSymbol[s] (*Keys and PrintSymbol are defined above*)
Other resources
Here's a list of interesting links for learning purpose:
A collection of Mathematica learning resources
Updated here: https://mathematica.stackexchange.com/a/259/66