Replace symbols with values without evaluation
Using OwnValues
and HoldForm
:
{a = 7, b = 5, c = 6};
HoldForm[(a + b)/c] /. OwnValues@a /. OwnValues@b /. OwnValues@c
(7 + 5)/6
With[{a = a, b = b, c = c}, HoldForm[(a + b)/c]]
(7 + 5)/6
Assuming that variables are already defined and you don't want to bother with listing the symbols, and you want to have a function that does it in one go:
Attributes[hold] = {HoldAll};
hold[x_] := HoldForm@x /. Cases[Hold@x, s_Symbol :> (HoldPattern@s -> s), Infinity];
hold[(a + b)/c]
(7 + 5)/6
Hold[(a + b)/c] /. {a -> 1, b -> 3, c -> 4} /. Hold -> Defer
(* (1 + 3)/4 *)
Hold[(a + b)/c] /. {a -> 1, b -> -3, c -> 4} /. Hold -> Defer
(* (1 - 3)/4 *)
Hold[(a + b)/c] /. {a -> 1, b -> -3, c -> -4} /. Hold -> Defer
(* -(1/4) (1 - 3) *)
Edit: answer rewrite
This question in its base form is a duplicate, but since I cannot find the original, and since you extended the question to something more unique than what I recall, I shall provide a short answer.
You asked:
I know this a probably even harder, but would it be possible to output
(7+5)/(-6)
instead of-(1/6)*(7+5)
whenc=-6
?
For that kind of control see for example: Returning an unevaluated expression with values substituted in
Combining that with RuleCondition
, described in Replacement inside held expression, we can use:
SetAttributes[{defer, fill}, HoldAll]
MakeBoxes[defer[args__], fmt_] := Block[{Times}, MakeBoxes[Defer[args], fmt]]
fill[expr_] := defer[expr] /. x_Symbol :> RuleCondition[x]
Now:
{a, b, c} = {7, 5, -6};
fill[(a + b)/c]
(7+5)*-(1/6)
Because this uses Defer
you can use the output of fill
as input and it will fully evaluate.