Skip to main content
2 of 3
added 1 characters in body
Szabolcs
  • 236.5k
  • 31
  • 641
  • 1.3k

You are looking for partial evaluation. Perhaps, there is a shorter way, but here is one (rather subtle):

Clear[evalAtPattern]
$evalAtPattern[expr_, p_] :=
   expr /. pt : p :> With[{pp = pt}, pp /; True];

Clear[formula];
formula[x_List] :=
  evalAtPattern[
    Defer[(x[[1]] - x[[2]]) + (x[[3]] - x[[4]])],
    HoldPattern[x[[_]]]];

Now,

formula[{1, 2, 3, 4}]

(* (1 - 2) + (3 - 4) *)

And the output code can be executed. The solution combined injecting evaluated pieces inside held expressions via Trott - Strzebonski technique, and the use of Defer.

Leonid Shifrin
  • 114.9k
  • 16
  • 333
  • 424