Matt Hogancamp
Matt Hogancamp

Reputation: 111

Composing functions of functions in Mathematica

I would like define an operator in which the input and output are each functions. For example, say I have

op1[f_,x_,y_,z_]:= f[y,x,z]
op2[f_,x_,y_,z_]:=f[x,z,y]

I would like to compose op1 and op2 to obtain the operator which sends f(x,y,z) to f(z,x,y), for example. However, expressions such as op1[op2[f,x,y,z],x,y,z] are not properly interpreted by Mathematica.

At the moment the only fix is

g[x_,y_,z_]:=op2[f,x,y,z];
result[x_,y_,z_]:=op1[g,x,y,z]
  1. Vague question: how do I make this less clumsy?

  2. Less vague: Is there the notion partial evaluation in Mathematica, so that something like A[f,-,-,-] is properly interpreted as a function of 3 variables?

Upvotes: 1

Views: 570

Answers (2)

ogerard
ogerard

Reputation: 745

First, the way you write op1 and op2, they do not operate on f, and do not create a function, just an expression with that function. That's ok but it explains why you do not obtain what you want.

As a middle ground you can do this:

 In[1]:= myop1[f_][x_, y_, z_] := f[y, x, z];

 In[2]:= myop2[f_][x_, y_, z_] := f[x, z, y];

 In[3]:= myop2[myop1[g]][a, b, c]

 Out[3]= g[c, a, b]

This is quite close to what you want.

Upvotes: 2

Sven Koschnicke
Sven Koschnicke

Reputation: 6711

I think you can use Composition for that: http://reference.wolfram.com/language/ref/Composition.html

Composition[op1,op2][x,y,z]

In general refer to http://reference.wolfram.com/language/guide/FunctionalProgramming.html for functional programming related features.

Upvotes: 0

Related Questions