7
$\begingroup$

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?

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

3 Answers 3

8
$\begingroup$

Try this:

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

??BB

enter image description here

$\endgroup$
1
  • 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
    Commented Feb 8, 2014 at 21:13
2
$\begingroup$

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
$\endgroup$
1
$\begingroup$

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].

$\endgroup$
1
  • $\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$ Commented Sep 21, 2013 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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