Message Boards Message Boards

0
|
3119 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Why should I use x_ and not x or _ in function definitions?

Posted 2 years ago

I know Blank[] is matching every expression (at the beginning it wasn't very intuitive for me as a developer, since when we studied how to write compilers there was a blank expression concept which was "really blank").

Anyway, I'm trying to understand why I can't write the first or second expression and I have to write the third one.

f[x] := (x + 1)^2
f[_] := (_ + 1)^2
f[x_] := (x + 1)^2
POSTED BY: Gianluigi Salvi
3 Replies

Thanks!!

POSTED BY: Gianluigi Salvi
Posted 2 years ago

WL is a term rewriting system based on patterns and replacements. Evaluation substitutes patterns with their replacement. (This is a simplified view of evaluation, it is a lot more complex).

(* In this example the pattern is literal f[x] so that is the only pattern that will match it *)
ClearAll[f, x, y]
f[x] := (x + 1)^2

f[x]
(* (1 + x)^2 *)

f[y]
(* f[y] *)

(* The Blank is not bound to a symbol so the replacement cannot refer to the bound value *)
ClearAll[f, x]
f[_] := (_ + 1)^2

f[x]
(* (1 + _)^2 *)

(* Blank is bound to x so x can be used in the replacement *)
ClearAll[f, x, y]
f[x_] := (x + 1)^2

f[y]
(* (1 + y)^2 *)

Take a look at this video for an explanation of function definition and evaluation.

POSTED BY: Rohit Namjoshi

The first matches the literal 'x', and for the second one the problem is that you didn't give the input (the _) a name, so it can not be inserted (transformed to) on the right.

POSTED BY: Sander Huisman
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