2

Szabolcs provided an elegant answer to my previous question about printing executable code that uses Defer:

SetAttributes[echo, HoldAll]
echo[expr_] := (CellPrint@ExpressionCell[Defer[expr], CellDingbat -> ">"]; expr)

I'd like to tweak it a little if possible, to not print out options that aren't set. Here is a typical example of the kind of application I have in mind. ex2 is a function that calls NDSolve and takes an optional argument opts, which can pass options to NDSolve.

ex2[eqns_, unks_, tmax_, opts___?OptionQ] := Module[{ndsolveopts},
  ndsolveopts = NDSolveOpts /. Flatten[{opts, Options[ex2]}];
  With[{options = Evaluate[Sequence @@ ndsolveopts]},
    echo@NDSolve[eqns, unks, {t, 0, tmax}, options]]
];
Options[ex2] = {NDSolveOpts -> {}};

This works as expected:

ex2[{n'[t] == n[t] (1 - n[t]), n[0] == 0.01}, {n}, 10,
  NDSolveOpts -> {AccuracyGoal -> 16}]

> NDSolve[{n'[t] == (1 - n[t]) n[t], n[0] == 0.01}, {n}, {t, 0, 10}, AccuracyGoal -> 16]

{{n -> InterpolatingFunction[...]}}

This includes an ugly Sequence[] that I'd like to not see:

ex2[{n'[t] == n[t] (1 - n[t]), n[0] == 0.01}, {n}, 10]

> NDSolve[{n'[t]==(1 - n[t]) n[t],n[0] == 0.01}, {n}, {t, 0, 10}, Sequence[]]

{{n -> InterpolatingFunction[...]}}

Is there anyway to modify echo to prevent its output?

This post shows how to change a part of an expression inside Defer. Can I delete part instead?

Chris K
  • 20,207
  • 3
  • 39
  • 74

1 Answers1

1

You could use DeleteCases:

SetAttributes[echo,HoldFirst];
echo[expr_]:=(
    CellPrint @ ExpressionCell[
        DeleteCases[Unevaluated@Defer[expr], Verbatim[Sequence][], {2}],
        CellDingbat->">"
    ];
    expr
)
Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • My other uses of this function require replacing the levelspec {2} with Infinity but this is great, thanks! – Chris K Dec 04 '17 at 20:13