Re: How to Return from within a Table[]-Command?
- To: mathgroup at smc.vnet.net
- Subject: [mg33760] Re: [mg33728] How to Return from within a Table[]-Command?
- From: BobHanlon at aol.com
- Date: Thu, 11 Apr 2002 02:14:18 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
In a message dated 4/10/02 1:57:52 AM, dmueller at mathematik.uni-kassel.de
writes:
>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.
>
Throw and Catch work
Clear[divide2];
divide2[lst_?VectorQ] :=
Module[{i=1},
Catch[If[IntegerQ[#],
i++/2,
Throw["vector not valid"]]& /@ lst]];
divide2[{2,3,6}]
{1/2, 1, 3/2}
divide2[{2,3,a}]
"vector not valid"
However, if all you want to verify is some test of the
elements then a pattern will work and is more efficient
since it does not do any evaluations unless the results
are needed
Clear[divide2];
divide2[x:{__Integer}] := Range[Length[x]]/2;
divide2[x_] := "vector not valid";
divide2[{2,3,6}]
{1/2, 1, 3/2}
divide2[{2,3,a}]
"vector not valid"
Bob Hanlon
Chantilly, VA USA