Re: Do we need a When function?
- To: mathgroup at smc.vnet.net
- Subject: [mg132411] Re: Do we need a When function?
- From: Bob Hanlon <hanlonr357 at gmail.com>
- Date: Mon, 10 Mar 2014 04:40:13 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-outx@smc.vnet.net
- Delivered-to: mathgroup-newsendx@smc.vnet.net
- References: <20140308074231.0A4506A0B@smc.vnet.net>
You can use PatternTest ( p?test ) or Condition ( patt /; test ) Clear[f1, f2, f3, f4] f1[x_?NumericQ] = "success"; f1 /@ {x, 1, Pi, Infinity} {f1[x], "success", "success", f1[=E2=88=9E]} f2[x_?(NumericQ[#] &)] = "success"; f2 /@ {x, 1, Pi, Infinity} {f2[x], "success", "success", f2[=E2=88=9E]} f3[x_ /; NumericQ[x]] = "success"; f3 /@ {x, 1, Pi, Infinity} {f3[x], "success", "success", f3[=E2=88=9E]} f4[x_] := "success" /; NumericQ[x]; f4 /@ {x, 1, Pi, Infinity} {f4[x], "success", "success", f4[=E2=88=9E]} The tests or conditions can be any expression that evaluates to True or False. Bob Hanlon On Sat, Mar 8, 2014 at 2:42 AM, David Bailey <dave at removedbailey.co.uk>wrote: > Dear All, > > Recently I wanted to create an expression that only evaluated when x was > a number. Obviously, one way to do that is to write something like: > > If[x<1000000000000,f[x]] > > This will stay unevaluated until x is assigned to a number - as required > - but it is very ugly because it makes it hard to understand what is > going on. > > More generally, it would be nice to write an expression that will only > evaluate when an expression is true. I solved that by writing a function > When: > > SetAttributes[When, HoldAll]; > When[cond_, val_] := val /; cond > > However, my point is that this construction is sufficiently useful that > it should be built in to Mathematica, and my solution might not be > obvious to all users. > > Am I missing a simpler solution? > > Do others agree that this is an omission in the language? > > David Bailey > http://www.dbaileyconsultancy.co.uk >
- References:
- Do we need a When function?
- From: David Bailey <dave@removedbailey.co.uk>
- Do we need a When function?