Aside: No, pinv
is considerably slower than this, but it is more accurate. See Efficient way of doing linear regression - #33 by stevengj
I think you’re making life complicated for yourself. Just compute the pseudo-inverse (or whatever) once and store it in a variable to re-use it. The code will be a lot clearer and simpler than trying for some magic syntax.
Expecting the compiler to figure out that a complicated calculation like this can be re-used is unrealistic and likely to be fragile even if it worked in some cases — to do an optimization like this, the compiler needs to be able to prove that it can never change any results, which is more delicate than you seem to realize. This is true in any language, not just Julia.