1
$\begingroup$

I need to do the following transformation that

pick[a,b] -> ex[c|->{c[a],c[b]}]

ex is a function that accepts a function as parameter which returns a list when called.

ReplaceAll replaces all pick at once. But I only want to expand my expression one at a time. For example

pick[1,2]+pick[3,4] -> ex[Function[c, {c[1], c[2]}]] + pick[3, 4]

Then if I apply the transformation the second time, it becomes

ex[Function[c, {c[1], c[2]}]] + ex[Function[c, {c[3], c[4]}]]

So I've invented the following function

ExpandPick[exp_] := Module[{p, x, y, co},
  p = FirstPosition[exp, pick[x_, y_]];
  x = exp[[Sequence @@ p]][[1]];
  y = exp[[Sequence @@ p]][[2]];
  Print[x];
  Print[y];
  ReplacePart[exp, p -> ex[ Function[co,  {co[x], co[y]}]]]
  ]

ExpandPick[pick[a, b] + pick[c, d]]

But the output is

ex[Function[co$, {co$[x$227772], co$[y$227772]}]] + pick[3, 4]

x$227772], y$227772 are real eyesores. As I'm working on symbolic level, I need Mathematica to show a instead of x$227772.

How can I do so?

$\endgroup$

3 Answers 3

1
$\begingroup$

Your problem comes from "Function" having the attribute "HoldAll". Therefore, what you have to do, is to wrap "Funtion" with "Evaluate":

ExpandPick[exp_] := Module[{p, x, y, co},
  p = FirstPosition[exp, pick[x_, y_]];
  x = exp[[Sequence @@ p]][[1]];
  y = exp[[Sequence @@ p]][[2]];
  Print[x];
  Print[y];
  ReplacePart[exp, 
   p :> Evaluate@ex[Function[co, Evaluate@{co[x], co[y]}]]]
  ]

ExpandPick[pick[a, b] + pick[c, d]]

enter image description here

$\endgroup$
1
$\begingroup$

Why not this?

pick[args___] := Map[#, {args}] &
$\endgroup$
1
$\begingroup$

Use With instead of Module?

ClearAll[a, b, c, d, pick, ex, co]

ExpandPick[exp_] := With[{
   p = FirstPosition[exp, _pick]
   }, With[{
    x = First@Extract[exp, p],
    y = Last@Extract[exp, p]
    },
   ReplacePart[exp, p :> ex[Function[co, {co[x], co[y]}]]]]]
$\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.