Message Boards Message Boards

0
|
4545 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Replacement in a condition /;

Posted 10 years ago

How do I make this work intuitively?

f[x_] := x^2 /; a>0

f[2] /. a->1

I want the answer to be 4 because 1>0 is True, but it does not work. It works if I make a_ an argument of f, but I don't want to for various reasons.

POSTED BY: Richard Klopp
6 Replies
Posted 10 years ago

Here is idiomatically correct version of your code that works:

f[x_] := x^2 /; a > 0

Block[{a = 1}, f[2]]
POSTED BY: Alexey Popkov

This works, but it is awkward:

g[x,a]:=x^2 /; a>0

h

h[2]/.a->1

4

POSTED BY: Richard Klopp

The approach you tried doesn't work because f[2] is evaluated before the replacement rule is applied.

An approach like the following certainly works:

Module[{fResult},
 a = 1;
 fResult = f[2];
 a =.;
 fResult
 ]

But that's probably too ornate for whatever you are doing given that you don't want to define an f[x_,a_].

Another approach is to define f as

f[x_] := x^2

and then to execute

If[a > 0, f[2]] /. a -> 1

or

If[a > 0, f[2],alternative] /. a -> 1

I'm sure there are lots of approaches, but which one you might use depends on the particular problem that you are coding.

POSTED BY: David Reiss

Block is indeed the correct solution.

POSTED BY: David Reiss

Why so complicated? How about simply:

f[x_] := If[a > 0, x^2, "whatever"]

this works exactly as intended:

a=.;
f[2] /. a->1

Yours Henrik

POSTED BY: Henrik Schachner

Note that that was one of my suggestions.

POSTED BY: David Reiss
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