1
$\begingroup$

This question already has an answer here:

I wrote a function

InversionF[f__] := Table[Function[x, 1 - ff[x]], {ff, {f}}]

I was thinking that for list of functions, it will create list of modified functions.

For one function it works:

InversionF[#^2 &]

gives

Function[y$, 1 - (#1^2 &)[y$]]

But for two functions it doesn't:

InversionF[#^2 &, #^3 &]

gives

{Function[x, 1 - ff[x]], Function[x, 1 - ff[x]]}

Although in first case I was expecting list of 1 element, which doesn't happen.

Why?

UPDATE

After restarting kernel, results became consistent but still not desired:

{Function[x, 1 - ff[x]]}
{Function[x, 1 - ff[x]], Function[x, 1 - ff[x]]}
$\endgroup$

marked as duplicate by Kuba Jul 22 '17 at 12:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ Perhaps you have old definitions hanging around. Try restarting the kernel. $\endgroup$ – Simon Woods Jul 22 '17 at 11:55
  • 1
    $\begingroup$ I found it didn't work for me even with just one function. Including With seemed to give me something sensible, though: InversionF[f__] := Table[With[{g = ff}, 1 - g[#] &], {ff, {f}}]... for reasons which baffle me. $\endgroup$ – aardvark2012 Jul 22 '17 at 11:59
  • $\begingroup$ @aardvark2012 any explanation for this? $\endgroup$ – Dims Jul 22 '17 at 12:17
  • $\begingroup$ So, following the linked topic: InversionF[f__] := Table[With[{ff = ff}, Function[x, 1 - ff[x]]], {ff, {f}}]. If you disagree with closing, let me know. $\endgroup$ – Kuba Jul 22 '17 at 12:44
1
$\begingroup$

Function has attribute HoldAll so everything inside of it is held unless you call the function. You need to evaluate ff away from Function and substitute:

InversionF[f__] := Table[Function[x, 1 - #[x]] &[ff], {ff, {f}}]

Maybe also call ff outside Function:

InversionF[f__] := Block[{x}, Table[Function[x, 1 - #] &[ff[x]], {ff, {f}}]]

Alternatively:

InversionF2[f__] := Fold[MapAt[#2, #, {All, -1}] &, {f}, {1 - # &, Evaluate}]
InversionF2[#^2 &, Function[x, x^3]]

{1 - #1^2 &, Function[x, 1 - x^3]}

$\endgroup$
  • $\begingroup$ This won't give a list of pure functions, which I want. $\endgroup$ – Dims Jul 22 '17 at 12:38
  • $\begingroup$ @Dims like the edit? $\endgroup$ – Coolwater Jul 22 '17 at 12:44

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