3
$\begingroup$

I was running into a strange error that boils down to this

Myfunction[List_]:= Transpose[{List}]
Test = {1, 2};
Myfunction[Test]

The output is

Transpose[{1, 2}[{1, 2}]]

This doesn't make sense to me because if I just run

Transpose[{Test}]

I get

{{1}, {2}}

Can anyone explain why the test of {1, 2} appears twice when I run Myfunction?

$\endgroup$
2
  • 3
    $\begingroup$ I'd say this is an interesting question (at least for me). Though we all know using built-in functions (in this case, List) as variable is bad practice, we don't have many questions about the possible side-effect caused by such bad practice, so +1. $\endgroup$ Commented Aug 20 at 1:54
  • 4
    $\begingroup$ If you do Evaluation->Analyze notebook, you will get this issue clearly pointed out. i.sstatic.net/23noS0M6.png $\endgroup$ Commented Aug 20 at 2:54

2 Answers 2

8
$\begingroup$

This is because the FullForm of {…} is List[…]:

{aaa} // FullForm
(* List[aaa] *)

So, what you've defined is the same as

Myfunction[List_] := Transpose[List[List]]

To make it clearer, you've defined something equivalent to

Myfunction[a_] := Transpose[ a[a] ]

I'd say this is a good example showing why using built-in functions as variables is dangerous :) .

$\endgroup$
4
$\begingroup$
FullForm[Hold[Myfunction[List_] := Transpose[{List}]]]
Hold[SetDelayed[Myfunction[
       Pattern[List, Blank[]]], (* 'List' is the name to substitute here *)
       Transpose[List[List]]]] (* Both 'List's are replaced in this expression *)

Or to be as specific as possible:

FullForm[{List}]
List[List]

You defined a substitution (Myfunction) which replaces all instances of List in its expression with the input. That it replaces both the explicit List inside the brackets and the implicit List provided by the brackets is expected (if not necessarily obvious or intuitive) behavior.

FullForm is useful for understanding things like this. It is also a good demonstration of why not to re-use built-in names (especially those with syntactic sugar that might hide them away) as parameter names.

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.