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

Posted 25 days ago
257 Views
|
3 Replies
|
2 Total Likes
|
 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 
3 Replies
Sort By:
Posted 25 days ago
 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.
 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.