# Define a function with a function for an input

I want to create the functions $even[f]$ and $odd[f]$ which will apply the formula $even[f(x)] = \frac{f(x)+f(-x)}{2}$ and $odd[f(x)]=\frac{f(x)-f(-x)}{2}$ for an arbitrary $f$.

I tried using

even[ff, x_] := (ff[x] + ff[-x])/2


But that doesn't seem to work. What would the correct approach to this be?

-
even[f_[x_]] := (f[x] + f[-x])/2 and odd[f_[x_]] := (f[x] - f[-x])/2 – RunnyKine Feb 18 '14 at 4:38
or like this: even[f_] := (f[#] + f[-#])/2 &; odd[f_] := (f[#] - f[-#])/2 & – Szabolcs Feb 18 '14 at 4:39
Neither approach is working for me at the moment. In the first approach mathematica doesn't evaluate anything, just leaving the even function with whatever its argument is, and in the second approach I have a lot of #'s that are left unevaluated as well. – R R Feb 18 '14 at 4:46
When I boot mathematica fresh and enter it in this is what I get:In[28]:= ClearAll[f, ff, even, x] In[29]:= even[f_[x_]] := (f[x] + f[-x])/2 In[30]:= f[x_] := x^2 + x In[35]:= even[f] even[f[x]] even[f[x_]] even[f[#]] Out[35]= even[f] Out[36]= even[x + x^2] Out[37]= even[x_ + x_^2] Out[38]= even[#1 + #1^2] – R R Feb 18 '14 at 5:12
Did you SetAttributes like I did? – RunnyKine Feb 18 '14 at 5:23

## 2 Answers

SetAttributes[{even, odd}, HoldAll];
even[f_[x_]] := (f[x] + f[-x])/2;
odd[f_[x_]] := (f[x] - f[-x])/2;


Usage

g[x_] := x + x^2;

even[g[x]]


x^2

OR as Szabolcs suggested using pure functions:

even[f_] := (f[#] + f[-#])/2 &;
odd[f_] := (f[#] - f[-#])/2 &


Usage

Using the same g as above

even[g][x]


x^2

-
It might be helpful to mention that Szabolcs' method requires calling even[g][x] instead of even[g[x]]. Also it doesn't require HoldAll. – Rahul Feb 18 '14 at 10:19

You said you tried using

even[ff, x_] := (ff[x] + ff[-x])/2


but I guess you forgot to put the underscore on the first argument. If you do

even[ff_, x_] := (ff[x] + ff[-x])/2


instead, then it works.

g[x_] := x + x^2;
even[g, x]


x^2

P.S. No SetAttributes necessary using this method.

-