2
$\begingroup$

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?

$\endgroup$

1 Answer 1

1
$\begingroup$

You could use DeleteCases:

SetAttributes[echo,HoldFirst];
echo[expr_]:=(
    CellPrint @ ExpressionCell[
        DeleteCases[Unevaluated@Defer[expr], Verbatim[Sequence][], {2}],
        CellDingbat->">"
    ];
    expr
)
$\endgroup$
1
  • $\begingroup$ My other uses of this function require replacing the levelspec {2} with Infinity but this is great, thanks! $\endgroup$
    – Chris K
    Dec 4, 2017 at 20:13

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.