5
$\begingroup$

Let's say I have a list of pure functions that are nice algebraic expressions: say

l = {(#1 - 1)&, (#1^2 + #1)&, (#1^3 - 1)&}

What's an easy way to get a pure function that will give the product of these expressions? For example, in the above I'd like to get a function f with

f = (#1 - 1)(#1^2 + #1)(#1^3 - 1)&

I've tried (Times @@ Identity @@@ l)&, but this just gives (#1 - 1)(#1^2 + #1)(#1^3 - 1). Essentially, it seems my difficulty is converting a List of Function expressions to a Function[Times[...]] expression, and I can't see how to "strip off" the functions without messing up the referencing of the Slot[1] expressions inside.

Thanks for any help.

$\endgroup$
3
  • $\begingroup$ @PinguinDirk, I was presuming that the OP wanted to keep it as a pure function. $\endgroup$ Commented Jul 4, 2013 at 8:28
  • $\begingroup$ I misread anyway, actually I am not too sure what the OP actually wants... maybe Function[x, Times @@ Through[l[x]]]? But thanks for pointing that out, @Jonathan Shock $\endgroup$ Commented Jul 4, 2013 at 8:36
  • $\begingroup$ @PinguinDirk Your suggestion gives what I want as well; the use of Through is clever. Thanks for your help! $\endgroup$
    – dvitek
    Commented Jul 4, 2013 at 8:49

2 Answers 2

9
$\begingroup$

Mapping First over your list will strip off the Function head. Then multiply them together with Apply[Times... and finally Apply[Function... makes the result a pure function. Use the final Apply so the argument to Function is evaluated first as Function has the attribute HoldAll.

Apply[Function,{Apply[Times, Map[First,l]]}]

Gives...

(-1+#1) (#1+#1^2) (-1+#1^3)&
$\endgroup$
2
  • $\begingroup$ Thanks so much! This works perfectly! $\endgroup$
    – dvitek
    Commented Jul 4, 2013 at 8:45
  • $\begingroup$ This can also be written: Function @@ {Times @@ First /@ l} $\endgroup$
    – Mr.Wizard
    Commented Jul 4, 2013 at 9:47
8
$\begingroup$

Here is another option:

l = {(#1 - 1) &, (#1^2 + #1) &, (#1^3 - 1) &};

Thread[Times @@ l, Function]
(#1 - 1) (#1^3 - 1) (#1^2 + #1) &

This has the benefit of not evaluating the body of the functions. For example:

l = {(#1 - 1) &, (#1^2 + #1) &, (Print["!"]; #1^3 - 1) &};

Thread[Times @@ l, Function]
(#1 - 1) (Print["!"]; #1^3 - 1) (#1^2 + #1) &

Note that the Print statement remains. Compare with:

Function @@ {Times @@ First /@ l}

!

(-1 + #1) (#1 + #1^2) (-1 + #1^3) &
$\endgroup$

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.