I am writing my own symbolic functions with custom symbolic properties.
So often I wish to introduce some automatic simplifications or evaluations, which return the same head as it's argument. This means I can't use normal function definition to avoid infinite recursion.
Suppose I with to create library for naive set theory. I am introducing MySet
head to represent sets.
For example, to create a set with a
, b
and c
elements, I will write
MySet[a,b,c]
and Mathematica will reply
{a,b,c}
since I defined head MySet
to be displayed in curly braces.
Of course
MySet[a,b,c] // FullForm
will give
MySet[a,b,c]
Now suppose I wish to remove duplicates automatically, since sets do not care of duplicates. So that if I wrote
MySet[a,b,b,c]
Mathematica would reply
{a,b,c}
How to accomplish that?
Currently I am writing two helper functions, like HasDuplicates
and RemoveDuplicates
and write something like that
MySet[x__] :=
MySet@@DeleteDuplicates[{x}] /;
HasDuplicates[{x}];
But this approach requires me to code nearly the same things in two places -- HasDuplicates
and RemoveDuplicates
functions.
How to avoid this? Is it possible to write this in some following manner:
MySet[x__] := Block[{...},
(* search for duplicates and remove them *)
If[ someweremoved,
MySet[y], (* with removed duplicates *)
MySet[x] (* with no modifications *)
];
];
The problem is that I can't prevent infinite recursion here since MySet
is called again and again in any case.
Can I prevent recursion by force? I.e. tell somehow, that expression returning should not be reevaluated?
Or may be I can implement Condition
somehow in programming style?
Or may be there is a way to code simplifications somehow?
UPDATE
The set is just a sample. My question is about general solution, suitable for ANY case of simplifications. The general sign of simplification is just was it done something or not. We can't assume we can compare some short list or count some.
Format[set[aa__]] = {aa};
so it looks more mathematical? $\endgroup$