Message Boards Message Boards

0
|
4129 Views
|
3 Replies
|
8 Total Likes
View groups...
Share
Share this post:

Why can't define a function as f[n_ +1]:=n^2?

Posted 10 years ago

I am looking for an alternative to f

Thanks

POSTED BY: Robert Otome
3 Replies

@Sander's example is very clear. This type of definition returns an up value of the symbol Plus.

POSTED BY: Shenghui Yang

Hi Robert, you can make it work; but not for all input:

ClearAll[f]
f[Plus[n_,1]]:=n^2
f[a+1]
f[3+1]

So it would work for a+1 (where a is a symbol). If a is a number, then it will first compute the sum, and then call the function; the function does not match the pattern then.

POSTED BY: Sander Huisman

What's wrong with f[n_]:=(n-1)^2?

f[n_ + 1] := n^2 is a valid definition but doesn't mean what you expect here. To understand why, you can read an introduction to pattern matching here.

POSTED BY: Szabolcs Horvát
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