If func is a function, and lst is a list, then I would LOOOOVE to get a warning if I enter
func[[i]] or lst[x] …
It’s a common error (at least for me), and it would save a me a lot of time if I got a warning when I did that.
Thanks.
If func is a function, and lst is a list, then I would LOOOOVE to get a warning if I enter
func[[i]] or lst[x] …
It’s a common error (at least for me), and it would save a me a lot of time if I got a warning when I did that.
Thanks.
While I agree it would be nice to have a helpful reminder, a potential problem is that they can be legitimate constructs: Try
tmp = {Cos, Sin, Tan}[Pi]
and
Through[tmp]
and then try
func = Function[{q}, q^2]
func[[2]]
list[[undefinedSymbol] ] will throw a warning.
For me I already get an error for func[[i]]:
In[20]:= func[x_] := x^2 + 2
In[21]:= func[[2]]
During evaluation of In[21]:= Part::partd: Part specification func[[2]] is longer than depth of object.
Out[21]= func[[2]]
So then the problem comes when using a List as the head of an expression. One way to make sure a message is issued for that case would be to define $Post:
In[22]:= list::notfunc = "Warning: list used as a function.";
$Post = ReplaceAll[x : (_List)[arg___] :> (Message[list::notfunc]; x)];
In[24]:= list = {1, 2, 3, 4};
In[25]:=list[3]
During evaluation of In[24]:= list::notfunc: Warning: list used as a function.
Out[25]= {1, 2, 3, 4}[3]
When you said function in your original post, I misinterpreted what you meant:
The two expressions
funcPattern[x_] := x^2 + 1
and
function = Function[{x}, x^2 + 1]
have the same behavior to the user, but they are different beasts. (The first one has “DownValues”).
Notice that the first is a definition:
?funcPattern
and the second is an assignment.
?function
They are both called “functions” unless one is being very picky. I am not sure what people at WRI call them when they are being picky, but I would say the first “is a held pattern” and the second “is a function”
The difference also becomes apparent when you do this:
function[[2]]
and
funcPattern[[2]]