Message Boards Message Boards

0
|
4481 Views
|
3 Replies
|
6 Total Likes
View groups...
Share
Share this post:

A warning when treating list as a function, or visa versa?

Posted 3 years ago

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.

POSTED BY: David Golber
3 Replies

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]]
POSTED BY: W. Craig Carter

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]
POSTED BY: Jason Biggs

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.

POSTED BY: W. Craig Carter
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract