See this example:

AA = {x} \[Function] Normalize[x]
BB = {x} \[Function] Evaluate[AA[x]*5]

I need BB to be Normalize[x]*5.

Some context:I call evaluate because I'm using CForm later to do some optimizations, so my functions need not to call other user-defined functions which would translate into something that is not really valid C code.

Normalize though just evaluates to a version which makes some sense only for complex numbers, this is not what the definition of Normalize does... Also, afaik Evaluate doesn't take assumptions, so I don't know how to "hint" it not to incorrectly expand Normalize...

I've tried various hold/replace/single step evaluate tricks, all not working. Any ideas?

  • 1
    $\begingroup$ Regarding code generation, here I described a generalization of a technique presented in one of the answers, which might be relevant. $\endgroup$ – Leonid Shifrin Sep 21 '13 at 10:40

Try this:

AA[x_] := Normalize[x];
Hold[BB[x_] := 5 AA[x]] /. DownValues[AA] // ReleaseHold


enter image description here

  • 1
    $\begingroup$ Great stuff as usual, but you don't need the Hold/ReleaseHold pair; Unevaluated will do: Unevaluated[BB[x_] := 5 AA[x]] /. DownValues[AA] $\endgroup$ – Mr.Wizard Feb 8 '14 at 21:13

Using the function ExpandCode defined here, you can expand any code that you want, for example expand all functions which name consist in upper case letters.

AA[x_] := Normalize[x];  
ExpandCode@Hold[Bb[x_] := 5 AA[x]] // ReleaseHold
Bb // DownValues

If you need BB to be Normalize[x]*5 explicitly, then use

AA[x_] := Normalize[x]

BBtemp[x_] := 5*AA[x]

BB[x_] = Hold[BBtemp[x]] /. DownValues[BBtemp] /. DownValues[AA]

(*Hold[5 Normalize[x]]*)

Unfortunately, when you act by ReleaseHold on it, it becomes 5 x/Norm[x].

  • $\begingroup$ That's the struggle, I can Hold but that will mean that CForm will contain the Hold which will then again screw my code-generator... I guess I could define a Hold function in the C preprocessor that just ignores the Hold though... Mhm... $\endgroup$ – Angelo Pesce Sep 21 '13 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.