1
$\begingroup$

I want to replace a function with either one or two functions and also combine their arguments.

Say I have an original expression

expr = u[i + 1] r[i] r[i-1]

Then I want to to replace u[i] with g[i+1] f[i-1] in such a way that expr becomes

g[i+2] f[i] r[i] r[i-1]

If I were to feed in f[i+1], then I would like to replace u[i] with f[i+1] so expr becomes f[i+2] r[i] r[i-1].

I tried using pure functions by saying

q[h_] := expr /. {u -> Function[x, h[x]]};

but this didn't work, instead just putting (h[x])[i+1] r[i] r[i-1] when I enter a function h[x].

The expression expr is a simple example, so I don't want to separate them into functions and arguments by hand.

$\endgroup$
2
  • $\begingroup$ I'm confused by "I want to replace u[i] with g[i+1] f[i-1] so expr becomes g[i+2] u[i] r[i] r[i-1]. I would read "I want to replace u[i] with g[i+1] f[i-1]" to mean that the result should be g[i+2] f[i] r[i] r[i-1]. Is that right? $\endgroup$
    – march
    Commented Aug 19, 2015 at 17:20
  • 1
    $\begingroup$ I can't seem to follow your replacement examples. Can you clarify? For instance, what do you mean when you say that you want to "feed in" a certain expression? Feed it in to what? $\endgroup$
    – MarcoB
    Commented Aug 19, 2015 at 17:21

2 Answers 2

1
$\begingroup$

If you are okay with using pure functions, you can do the following.

expr = u[i + 1] r[i] r[i - 1];

replaceuWith[expr_, h_Function] := expr /. u[x_] :> h[x]

Alternatively,

replaceuWith[expr_, h_Function] := expr /. u -> h

Then,

replaceuWith[expr, g[# + 1] f[# - 1] &]
(* f[i] g[2 + i] r[-1 + i] r[i] *)

replaceuWith[expr, f[# + 1] &]
(* f[2 + i] r[-1 + i] r[i] *)

If you're uncomfortable with Slots (i.e. #), then you can also call this as

replaceuWith[expr, Function[{i}, g[i + 1] f[i - 1]]]
(* f[i] g[2 + i] r[-1 + i] r[i] *)

A slightly more general version that also allows you to select what function name to replace:

repl[expr_, h_Function, x_Symbol] := expr /. x -> h

Then,

repl[expr, f[# - 1] &, u]
(* f[i] r[-1 + i] r[i] *)

repl[expr, f[# - 1] &, r]
(* f[-2 + i] f[-1 + i] u[1 + i] *)
$\endgroup$
2
$\begingroup$

I believe you want

expr = u[i + 1] r[i] r[i - 1]
expr /. u[n_] :> g[n + 1] f[n - 1]
(*  f[i] g[2 + i] r[-1 + i] r[i] *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.