Group Abstract Group Abstract

Message Boards Message Boards

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

Replacement in a condition /;

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

This works, but it is awkward:

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

h

h[2]/.a->1

4

POSTED BY: Richard Klopp

Note that that was one of my suggestions.

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

Block is indeed the correct solution.

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