Re: Simple Module Code

*To*: mathgroup at smc.vnet.net*Subject*: [mg49562] Re: [mg49510] Simple Module Code*From*: DrBob <drbob at bigfoot.com>*Date*: Fri, 23 Jul 2004 06:00:26 -0400 (EDT)*References*: <200407220645.CAA21041@smc.vnet.net>*Reply-to*: drbob at bigfoot.com*Sender*: owner-wri-mathgroup at wolfram.com

I'll assume your data is something like this: data=Array[Random[Integer,{0,4}]&,{20,2}] {{1,1},{1,3},{4,4},{4,3},{2,2},{4,0},{1,3},{1,1},{3,1},{0,3},{4,3},{2,4},{ 0,2},{3,2},{4,2},{4,0},{4,3},{2,2},{0,4},{4,2}} and you're trying to select the second elements where the first element is 1. First of all, there's no point in Module[{},...], since the purpose of Module is to make things in that empty set local (all _none_ of them). If that were the only issue, you could write the code as splitData[data_, list_, i_] := ( Print["In Split Data ", i]; If[data[[i, 1]] == 1, list = AppendTo[list, data[[i, 2]]]]; Print["Length of list is: ", Length[list]] ) Secondly, list=AppendTo[list,x] is exactly the same thing as AppendTo[list,x], so it's equivalent to write splitData[data_, list_, i_] := ( Print["In Split Data ", i]; If[data[[i, 1]] == 1, AppendTo[list, data[[i, 2]]]]; Print["Length of list is: ", Length[list]] ) Third, I don't see error messages about recursion; I see error messages saying "...is not a variable with a value, so its value cannot be changed". This is because named patterns like "list" in your "splitData" function can't be modified. So the code can't work at all. Fourth, there IS an infinite recursion going on (perhaps I have that error message switched off). It occurs because the variable "list" that you're passing to splitData is undefined (as far as I can see from your post), so the list=AppendTo[list,...] statement defines list in terms of itself. You'd need to define list={} initially, before calling SplitData the first time. With all that in mind, here's a solution that's close to your own attempt: splitData[data_, list_, i_] := If[data[[i, 1]] == 1, Append[list, data[[i, 2]]], list] list = {}; Do[list = splitData[data, list, i], {i, 1, Length[data]}] list {1,3,3,1} But here's a much better way: Cases[data, {1, a_} -> a] {1,3,3,1} Bobby On Thu, 22 Jul 2004 02:45:44 -0400 (EDT), Doug <umdougmm at hotmail.com> wrote: > Does anyone know why the following code would not work inside a module? > list = AppendTo[list, data]; > > here's the exact code > splitData[data_, list_, i_] := Module[{}, > Print["In Split Data ", i]; > > If[data[[i,1]]==1, list = AppendTo[list, data[[i, 2]]]]; > Print["Length of list is: ", Length[list]]; > ] > > which is called by: > Do[splitData[data, list, i], {i, 1, Length[data]}] > > It complains about to many recursions, yet on the command line alone, > list = AppendTo[list, data]; > works just fine? > > Thanks > Doug > > > > > -- DrBob at bigfoot.com www.eclecticdreams.net

**References**:**Simple Module Code***From:*"Doug" <umdougmm@hotmail.com>