4
$\begingroup$

I checked several cases and saw that two functions are equivalent in these samples. However, are the two equivalent in all cases? Is there a way to check that?

Explicit function:

  g[x_]= π
  h[_] = π
$\endgroup$

1 Answer 1

8
$\begingroup$

Yes, they are equivalent.

_ is a pattern that matches any expression.

x_ is the same thing, with a name, x. The pattern name can be used in two ways.

The most common way is to refer to it on the right hand side of the definition or rule. For example, f[x_] := x^2. If we are not using the matched expression in the right hand side, there's no reason to name the pattern.

The other situation is when two sub-patterns have the same name. This is used to require them to match the same expression. For example, {x_, x_} matches {1,1} but not {1,2}. In contrast, {_, _} matches both {1,1} and {1,2}.

Neither situation applies to your example. The pattern name is never used for anything. Thus there's no purpose of naming the pattern.

Further reading:

$\endgroup$
1
  • $\begingroup$ Thanks for the thorough answer! I've just known that the pattern is called blank. $\endgroup$
    – emnha
    Jan 31, 2016 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.