Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am learning Mathematica in random order by reading its documentation. This approach is what I like most when learning new things.

Consider the following 2 cases.

Syntax A:

Format[Foo[x_,y_]]:=MatrixForm[{{x},{y}}]
Foo[1,2]

Syntax B:

Foo[x_,y_]:=Format[MatrixForm[{{x},{y}}]]
Foo[1,2]

My confusion is about why can we use Format on the left side? It seems to be counter intuitive as in most programming language, definition should be on the right side. Could you explain why?

share|improve this question
1  
I had trouble grasping "definitions" like these, too. Until I stopped thinking about them as "definitions" and started to see them as "replacement rules", i.e. telling the interpreter "if you see something that matches the pattern on the left, replace it with that stuff on the right side of the :=". Then it started making sense. –  nikie Dec 31 '13 at 19:17

1 Answer 1

up vote 7 down vote accepted

The two definitions are not the same... it changes what kind of definition is associated with the symbols.

Consider the following:

Syntax 1:

ClearAll@Foo
Foo[x_, y_] := Format[MatrixForm[{{x},{y}}]]
DownValues@Foo

FormatValues@Foo
(* {} *)

Syntax 2:

ClearAll@Bar
Format[Bar[x_, y_]] := MatrixForm[{{x}, {y}}]
DownValues@Bar
(* {} *)

FormatValues@Bar


In the first case, the formatting rules are applied as DownValues to the function, which affects evaluation, whereas in the second case, the rules are associated with FormatValues. Syntax 2 is a better option if all you want to do is to change the appearance/formatting/presentation. However, Mathematica staying true to its principle of "everything is an expression", will allow you to define your function as in syntax 1.

share|improve this answer
3  
I must also note that Format[foo] by itself does nothing and just returns the input, thus syntax 1 is also pointless from the point of doing what the OP intended. –  rm -rf Dec 31 '13 at 19:00
    
Probably also worth mentioning that the output given by FormatValues[Bar] is actually displayed according to those same FormatValues, so the result may be a little misleading. Overall I don't really find Format all that useful. Definitions on MakeBoxes are much more versatile and less prone to unexpected problems (e.g. FormatValues-MakeBoxes continuous loop when one uses boxes in the FormatValues definitions). It seems to be a remnant from before the box language was introduced. –  Oleksandr R. Jan 1 at 20:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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