Skip to content
AgileLogics
4 min read

Comments and Style

Prerequisites: Defining functions

Comments

(* A comment *)
rate = 0.05; (* after code *)

(* Comments can span
   several lines, and (* nest *) safely. *)

(* compound[p, r, n]: value of p after n years at rate r *)
compound[p_, r_, n_] := p (1 + r)^n
compound[1000, rate, 2]
1102.5

There's only one comment syntax, (* ... *). In notebooks, text cells are the better place for longer explanations.

Usage messages

Document your functions the way built-ins are documented:

compound::usage = "compound[p, r, n] gives the value of p after n years at interest rate r.";
?compound

?compound now shows that description.

Style guidelines

  • Lowercase first letter for your own symbols (unitPrice); built-ins use PascalCase. Never use underscores in names.
  • Descriptive names, since the language itself uses full English words (StringLength, not strlen).
  • Prefer built-in functions and functional style — Total[list] rather than a loop, Select rather than If inside Do.
  • Use Module for local variables in every function longer than one line.
  • Break long expressions across lines with indentation, and put one definition per cell in notebooks.
  • Keep notebooks runnable top to bottom — restart the kernel (Evaluation → Quit Kernel) and use Evaluation → Evaluate Notebook to make sure it doesn't depend on something you deleted.
  • Keep exact numbers exact until the end, then use N.

What's next

You now know the core of the Wolfram Language. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with functional programming.