Question

How can the following be best accomplished in Mathematica?

 In[1] := Solve[f[2,3]==5,f ∈ {Plus,Minus,Divide}]

Out[1] := Plus
Was it helpful?

Solution

The desired expression syntax can be transformed into a set of Solve expressions:

fSolve[expr_, f_ ∈ functions_List] :=
  Map[Solve[(expr /. f -> #) && f == #, f] &, functions] // Flatten

Sample use:

In[6]:= fSolve[f[2,3] == 5, f ∈ {Plus, Subtract, Divide}]
Out[6]= {f -> Plus}

In[7]:= fSolve[f[4,2] == 2, f ∈ {Plus, Subtract, Divide}]
Out[7]= {f -> Subtract, f -> Divide}

The advantage of this approach is that the full power of Solve remains available for more complex expressions, e.g.

In[8]:= fSolve[D[f[x], x] < f[x], f ∈ {Log, Exp}]
Out[8]= {f -> ConditionalExpression[Log, x Log[x]∈Reals && x>E^ProductLog[1]]}

In[9]:= fSolve[D[f[x], x] <= f[x], f ∈ {Log, Exp}]
Out[9]= {f -> ConditionalExpression[Log, x Log[x]∈Reals && x>=E^ProductLog[1]],
         f -> ConditionalExpression[Exp, E^x ∈ Reals]}

OTHER TIPS

Please tell me if this does what you want:

findFunction[expr_, head_ ∈ {ops__}] :=
    Quiet@Pick[{ops}, expr /. head -> # & /@ {ops}]

findFunction[f[2, 3] == 5, f ∈ {Plus, Minus, Divide}]
(* Out[]= {Plus} *)

I'm not aware of a built-in function, but it's not hard to write one yourself. Here is one approach that you can use:

Clear@correctOperatorQ;
correctOperatorQ[expr_, value_, 
  operators_] := (expr == value) /. Head[expr] -> # & /@ operators

By the way, the correct operator for 2-3 is Subtract, not Minus. The result for your example:

correctOperatorQ[f[2, 3], 5, {Plus,Subtract,Divide}]
Out[1]={True, False, False}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top