RE: RE: How to Return from within a Table[]-Command?
- To: mathgroup at smc.vnet.net
- Subject: [mg33773] RE: [mg33759] RE: [mg33728] How to Return from within a Table[]-Command?
- From: "DrBob" <majort at cox-internet.com>
- Date: Tue, 16 Apr 2002 03:50:20 -0400 (EDT)
- Reply-to: <drbob at bigfoot.com>
- Sender: owner-wri-mathgroup at wolfram.com
Why not try something a lot simpler?
Divide2[L:{_Integer..}]:= Module[{i},i=1;i++/2&/@L]
Divide2[a_]:="vector not valid"
Bobby Treat
-----Original Message-----
From: Wolf, Hartmut [mailto:Hartmut.Wolf at t-systems.com]
To: mathgroup at smc.vnet.net
Subject: [mg33773] [mg33759] RE: [mg33728] How to Return from within a
Table[]-Command?
> -----Original Message-----
> From: Detlef Mueller [mailto:dmueller at mathematik.uni-kassel.de]
To: mathgroup at smc.vnet.net
> Sent: Wednesday, April 10, 2002 6:49 AM
> To: mathgroup at smc.vnet.net
> Subject: [mg33773] [mg33759] [mg33728] How to Return from within a
Table[]-Command?
>
>
> Hello,
>
> I wanted to scan trough al List, building a new
> List, but aborting, if one Element of the first
> List violates a special Condition ...
> say for example:
>
> Divide2[L_List] := Module[{},
> Table[
> If[IntegerQ[L[[i]]],
> i/2,
> Return["vector not valid."];
> ]
> , {i, 1, Length[L]}
> ]
>
> ...
>
> ]
>
> But this results:
>
> In[13]:= Divide2[{2,3,a}]
> Out[13]= {1/2, 1, Return["vector not valid."]}
>
> Wich is of course not what I want.
>
> Greetings
>
> Detlef
>
Detlef,
two suggestions:
(1) Catch and Throw:
In[1]:= Divide2a[L_List] :=
Catch[Module[{},
Table[If[IntegerQ[L[[i]]], i/2, Throw["vector not valid."];],
{i, 1, Length[L]}] + 0]]
In[2]:= Divide2a[{2, 3, a, 5}]
Out[2]= "vector not valid."
In[3]:= Divide2a[{2, 3, 4, 5}]
Out[3]= {1/2, 1, 3/2, 2}
(-) Issue an error Message:
In[4]:= Divide2b[L_List] :=
Module[{},
Table[If[IntegerQ[L[[i]]], i/2, Message[Divide2b::invalid]],
{i, 1, Length[L]}] + 0]
In[5]:= Divide2b::"invalid" = "vector not valid.";
In[6]:= Divide2b[{2, 3, a, 5}]
>From In[6]:= Divide2b::"invalid": "vector not valid."
Out[6]= {1/2, 1, Null, 2}
In[7]:= Divide2b[{2, 3, 4, 5}]
Out[7]= {1/2, 1, 3/2, 2}
Although you got the message, you also got an undesired Result.
Prevent this with
(2) Check:
In[8]:= Check[Divide2b[{2, 3, a, 5}], $Aborted, Divide2b::invalid]
>From In[8]:= Divide2b::"invalid": "vector not valid."
Out[8]= $Aborted
In[9]:= Check[Divide2b[{2, 3, 4, 5}], Null, Divide2b::invalid]
Out[9]= {1/2, 1, 3/2, 2}
If Divide2b is buried in a comprehensive calculation, which you want to
have
aborted totally, then wrap that into Check. Of course, instead of
$Aborted
you may return any value, Null e.g., which will not be printed.
--
Hartmut Wolf