4
$\begingroup$

Is there anything inherently different about defining a like this (with parentheses):

fibo[n_Integer]:=(Sum[Fibonacci[i], {i,0,n}] == Fibonacci[n+2]-1)

Or, like this (without parentheses):

fibo[n_Integer]:= Sum[Fibonacci[i], {i,0,n}] == Fibonacci[n+2]-1

If so, is there any advantage to using parentheses?

$\endgroup$
3
  • $\begingroup$ There is nothing syntactically special about function definitions. The two basic uses for parentheses is to override precedence (see the "Operator Precedence" table) and rarely to group things for readability. It is possible to write any expression without parentheses. For example SetDelayed[f[x_], a; b] instead of f[x_] := (a; b) (like @m_goldberg's example). The parentheses are removed when the expression is parsed, and other than the syntactical effect of grouping, they have no effect on evaluation.... $\endgroup$
    – Michael E2
    Jan 11, 2020 at 14:43
  • $\begingroup$ ...For instance, f[x_] := (a) and f[x_] := a result in the exact same internal definition. $\endgroup$
    – Michael E2
    Jan 11, 2020 at 14:44
  • $\begingroup$ The one with parentheses is clearer (more readable). Most people who use Mathematica probably could not immediately say which operator has higher precedence, := or == (even though after a bit of thinking it becomes clear that it would make no sense for := to have higher precedence than ==). If you found this code somewhere, the original author may not have been certain about which has higher precedence. It may have been less trouble to just use parentheses than to do the extra work to check. $\endgroup$
    – Szabolcs
    Jan 11, 2020 at 17:16

1 Answer 1

7
$\begingroup$

No, there is no difference in the case you give as an example. More generally, the need to use parentheses mostly comes up when the body of the function definition has head CompoundExpression.

For example,

foo[n_, k_: 42] := (SeedRandom[k]; RandomInteger[{n, 2 n}])
foo /@ Range[5]

{1, 3, 4, 7, 8}

foo[#, 1] & /@ Range[5]
>`{2, 3, 6, 8, 9}`
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.