Message Boards Message Boards

0
|
7054 Views
|
4 Replies
|
9 Total Likes
View groups...
Share
Share this post:

[?] Define a function that operates on patterns?

Posted 5 years ago

Hello everybody.

I'm trying to define a function that accepts a pattern as a parameter. After playing with HoldPattern and HoldAll attributes I'm out of ideas.

Is this at all possible? Here's an example of what I'd like to get:

Remove[f];
f[HoldPattern[Blank[Real]]] := 0; 
f[a_] := 1; SetAttributes[f, HoldFirst];
f[_Real] (* expecting to get 0 *)

Pure function will receive a pattern as expected.

Any ideas are welcome.

POSTED BY: Pavel Perikov
4 Replies

How about Verbatim?

Clear[f];
f[Verbatim[_Real]] := 0;
f[_] := 1;
{f[_Integer] (*1*), f[_Real] (*0*)}
POSTED BY: Gerli Jõgeva
Posted 5 years ago

Exactly! This is THE solution. Thank you!

POSTED BY: Pavel Perikov

Hi Pavel, see if any of these examples are useful for you:

Clear[f];
a := {f[a_] := 1};
f[HoldPattern[_]] := 0;

f[_Real]
a;
f[_Real]

i1

Clear[f];
f[a_] := a /. x_ /; x === pat -> 0;

f[pat]
f[3]
f[1]

i2

Clear[f];
f[a_: 10] := a;

f[]
f[2]
f[3]

i3

Clear[f];
f[a_] := a /. {pat -> 0, _ -> 1};

f[pat]
f[2]
f[3]

i4

Clear[f];
f[a_] := If[a \[Element] NegativeIntegers, 0, a];

f[2]
f[-2]
f[2.37]

i5

POSTED BY: Claudio Chaib
Posted 5 years ago

Thanks! Playing with those now.

POSTED BY: Pavel Perikov
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