Re: Which, If and "neither True nor False"
- To: mathgroup at smc.vnet.net
- Subject: [mg9689] Re: [mg9652] Which, If and "neither True nor False"
- From: Allan Hayes <hay at haystack.demon.co.uk>
- Date: Fri, 21 Nov 1997 01:31:25 -0500
- Sender: owner-wri-mathgroup at wolfram.com
"Paul E Howland" <PEHOWLAND at dra.hmg.gb> [mg9652] Which, If and "neither True nor False" writes: > I've just stumbled across a bug in some old code of mine, in which > I had a statement of the form: > > Which[ > a<b, DoSomething[], > a>c, DoSomethingElse[], > True, DoThis[] > ] > > which I assumed would call DoThis[] if neither a<b nor a>c were > True. However, what I didn't realise is that if a is undefined, > then the first two conditions are neither True nor False, and > Mathematica returns the whole Which statement unevaluated! > > The If statement has an optional fourth argument which is executed > if the test returns neither True nor False. Is it possible to do > the same in a Which statement? If not, why not?! Paul, How about the following kind of code? In[1]:= Which[TrueQ[U],a, True, b] Out[1]= b Here are some notes on Which. Which[test1, v1, test2, v2 ... testn, vn] evaluates as follows. For i = 1,2,... - evaluate testi to testi* - if testi* is True return the value of vi - if testi* is False remove testi and wi - if testi* is neither True nor False return Which[testi*, vi, test(i+1), v(i+1)... testn, vn] - if Which[] is reached return Null Which[test1, v1,..., True, v]gives the value of v when every testn gives False; Which[TrueQ[test1], v1 ... True, v]gives the value of v when no testn gives True. Examples In[2]:= F = False; T = True; U = vU; a = va; b = vb; {Which[F,a,T,b], Which[F,a,U,b,T,b], Which[TrueQ[U],a,True,b], Which[F,a,F,b], Which[] } Out[3]= {vb,Which[vU,b,T,b],vb,Null,Null} Allan Hayes hay at haystack.demon.co.uk http://www.haystack.demon.co.uk/training.html voice:+44 (0)116 2714198 fax: +44 (0)116 2718642 Leicester, UK