I'm trying to automatically optimize cases when the user evaluates Length[returnsList[x_]]
to instead use returnsLength
:
Clear[returnsList, returnsLength]
returnsList[a_] := ConstantArray[4,a]
returnsLength[a_] := a
returnsList /: Length[returnsList[a_]] := returnsLength[a]
That causes
ConstantArray::ilsmn: Single or list of non-negative machine-sized integers expected at position 2 of ConstantArray[4,a_].
TagSetDelayed::tagnf: Tag returnsList not found in Length[ConstantArray[4,a_]].
I'm surprised that returnsList
is evaluating. I tried SetAttributes[returnsList, HoldAll]
, but I get the same message (and I don't want to deal with Hold* unless I must).
The first example in ref/TagSetDelayed likewise breaks if I assign a value to g
, g[x_] := 2
, but this seems like the intended use case. What am I doing wrong?