When I write W[f_] := Integrate[f[x], {x, 0, π}] I may rightly conclude that
W[Sin] = 2, W[Cos] = 0, W[Log] = π (-1 + Log[π]) etc. But I am unable to define W[Sin + Cos] or W[Sin[Sin]] etc. Please help.
- 9,758
- 1
- 14
- 40
- 1,678
- 8
- 13
4 Answers
Make sure that you pass the right head/function to W. For example, Sin[Sin] @ x gives Sin[Sin][x], obviously unrecognizable by MMA, not to mention the aftermath evaluation of the integral. So one optional solution can be these
W[Sin[#] + Cos[#] &]
W[Sin @* Sin]
where @* is Composition.
- 9,783
- 3
- 20
- 41
Sin is something that takes an argument---Sin[7] is a number.
In contrast, Sin+Cos is not something that takes an argument! Your functional is trying to evaluate eg. (Sin+Cos)[7] which, without help, it does not understand.
So, you need to turn the argument of W into something that properly takes argument.
You could say
g[x]:= Sin[x]+Cos[x]
W[g]
for example. Or, you can do it anonymously using pure functions (#),
W[Sin[#]+Cos[#]&]
- 6,026
- 18
- 30
-
1I think this answer addresses the problem in a straightforward way and proposes two concise solutions that are idiomatic and honestly it's what I would expect someone to use. – yosimitsu kodanuri Sep 29 '20 at 06:32
The issue is that a functional operates on functions so in
W[f_] := Integrate[f[x], {x, 0, Pi}]
W needs to be fed a function. The expressions Sin+Cos or Sin[Sin] fail because these are not WL functions. Working in functional space we have the composition operators @* and \* but these are not sufficient when wanting to use WL's built-in functions which are geared to work with general expressions. But one way of co-opting WL's functions to operate in functional space is via FunctionalConstruct as follows:
FunctionalConstruct[op_, fs__] := Function[x, op @@ Through[{fs}[x]]];
FunctionalConstruct[op_] := op;
f = FunctionalConstruct[Plus, Sin, Cos];
ga = FunctionalConstruct[Sin, Sin];
gb = FunctionalConstruct[Sin@*Sin];
In some ways for these definite integrals it would be more natural to simply now write
Integrate[f, {0, Pi}]
Integrate[ga, {0, Pi}]
Integrate[gb, {0, Pi}]
in functional space but because in calculus it is often so useful to use dummy variables (indefinite integrals, turning expressions into desired functions w.r.t. x,y etc.) we get W to automatically apply the function to a dummy variable prior to performing the integral:
W[f]
W[ga]
W[gb]
2
Pi StruveH[0, 1]
Pi StruveH[0, 1]
- 6,076
- 26
- 46
For Sin + Cos you could define SubValues for CirclePlus:
CirclePlus[f_, g_][x] := f[x] + g[x]
Then:
W[Sin ⊕ Cos]
2
- 130,679
- 6
- 243
- 355
W[f_] := Integrate[f[x], {x, 0, Pi}]; W[Sin[#] + Cos[#] &]– cvgmt Sep 29 '20 at 03:25Throughcan do what you desire. But I think pure function is the most general way, rather than "case by case". – Αλέξανδρος Ζεγγ Sep 29 '20 at 04:54