5
$\begingroup$

A function needs to cope with many different forms of input, such as different heads (Plus, Times, Power, etc). Should the function be defined with multiple Mathematica delayed assignments (such as “PostScriptForm[Times[-1, thing_]] := …”) or with one large assignment, likely to be of the form PostScriptForm[thing_] := Which[ MatchQ[…], …, MatchQ[…], …, ]?

If the context helps, it is about PostScriptForm, which converts to PostScript as CForm converts to C.

Either form could work: which is more natural idiomatic Mathematica?

Edit: a related question. If multiple statements, as recommended in @eldo’s answer, should the statements be in different cells, or in the same cell separated by a blank line, or in the same cell without separations? Again, which is more natural idiomatic Mathematica?

$\endgroup$
2
  • $\begingroup$ Possible duplicate: (60846) $\endgroup$
    – Mr.Wizard
    Commented Jan 29, 2016 at 2:41
  • $\begingroup$ By the I addressed the performance issue in (2618) and I agree with eldo. $\endgroup$
    – Mr.Wizard
    Commented Jan 29, 2016 at 2:42

1 Answer 1

4
$\begingroup$

I usually prefer multiple function definitions. I find they are clearer to read, and they are usually faster, especially if you can avoid conditions, i.e. f[1] := ... is better than f[x_] /; x == 1 ...

Clear[f, g]

f[1] := 2
f[2] := 3
f[3] := 4
f[x_] := x

g[x_] := Switch[x, 1, 2, 2, 3, 3, 4, _, x]

f /@ Range[10^5]; // AbsoluteTiming // First

0.109200

g /@ Range[10^5]; // AbsoluteTiming // First

0.280801

$\endgroup$
2
  • $\begingroup$ Is the speed ordering general over most multi-case functions? I.e., have you previously tested some less-simple actual functions, with the same result? But, to argue the other possibility, would it be tidier to keep a function together and in one place by Which or Switch? $\endgroup$
    – jdaw1
    Commented Dec 27, 2015 at 22:18
  • $\begingroup$ Question edited to add a sub-question to your answer. $\endgroup$
    – jdaw1
    Commented Dec 27, 2015 at 23:44

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.