# One line definition of a symbol with plus-minus

I'm pretty new to Mathematica. I was wondering is there any way to define the symbol $H_\pm(x,y) = f(x) \pm g(y)$ in one line, so that $H_-$ or $H_+$ can be called separately? Something like: H_-[1,2] = f[1] - g[2] and H_+[1,2] = f[1] + g[2] .

Clear[H]

H[s_][x_, y_] :=
f[x] + Piecewise[{{-1, s === "-"}}, 1]*g[y] /; s === "+" || s === "-"


Examples:

{H["+"][x, y], H["-"][x, y]}

(*  {f[x] + g[y], f[x] - g[y]}  *)


Or

Clear[H]

H[s_][x_, y_] := f[x] + Sign[s]*g[y] /; Abs[s] === 1


Examples:

{H[1][x, y], H[-1][x, y]}

(*  {f[x] + g[y], f[x] - g[y]}  *)


The most robust way I know of would be to use the built in Notation package and write something like

Needs["Notation´"]

Symbolize[H±]  (* Be careful to use the Writing Assistant palette or other formatting guides s.t. the definition actually displays like you want it to and not Subscript or similar means *)

H±[x_, y_] := f[x] ± g[y] (* Same caveat about typesetting applies here as well *)


Then you get

In[1] := H±[1,2]
Out[1]:= f[1]±g[2]


In Mathematica it should look like this:

• Thanks for the answer, but please see the edit in the question. Commented Nov 4, 2015 at 20:09
• Defining the symbols should work analogously to my answer, or do you want to define both of them in one expression? Commented Nov 4, 2015 at 20:23
• Yeah I want to define both of them in one line. Because I have two really huge expression where things differ by plus-minus only, so I am looking for a compact way of writing both of them in one shot. Commented Nov 4, 2015 at 20:26

Here is a version that allows you to use $H_+$ and $H_-$ as requested:

(h:SubPlus|SubMinus)[H] ^:= With[
{hh=Replace[h, {SubPlus->Plus, SubMinus->Subtract}]},
hh[f[#1], g[#2]]&
]


A couple examples:

SubPlus[H][x, y]
SubMinus[H][2, 3]


f[x] + g[y]

f[2] - g[3]

This is how the above appears in a notebook:

Here is a variation on @Bob Hanlon's answer that uses functions instead of strings or integers.

h[op_Symbol][x_, y_] := op[f[x], g[y]]


This will work on any function that takes two or more arguments: Plus, Subtract, Times, Divide, Union, Intersection, and so on.

{h[Plus][m, n], h[Subtract][m, n], h[Times][m, n]}
(* {f[m] + g[n], f[m] - g[n], f[m] g[n]} *)


It can be restricted to just Plus and Subtract with MemberQ.

k[op_Symbol /; MemberQ[{Plus, Subtract}, op]][x_, y_] := op[f[x], g[y]]


k will only work for Plus and Subtract. For example, Times will not evaluate.

{k[Plus][m, n], k[Subtract][m, n], k[Times][m, n]}
(* {f[m] + g[n], f[m] - g[n], k[Times][m, n]} *)


Hope this helps.