Re: How to compile this module?

*To*: mathgroup at smc.vnet.net*Subject*: [mg80983] Re: How to compile this module?*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Thu, 6 Sep 2007 05:42:49 -0400 (EDT)*Organization*: The Open University, Milton Keynes, UK*References*: <fbliht$or0$1@smc.vnet.net>

P_ter wrote: > Hello, > I have some code in a Module and I would like to compile it so that Mathematica does not give complaints in execution: > myM[lst_, W_] := Module [ {i, j = 1, len = Length@lst, res}, > Reap[For[i = 1, i <= len, i++, > While[lst[[j]] - lst[[i]] <= W && j < len, j++]; > Sow[j - i]]; res] > ] > It works on this special constructed list (with a large number at the end): > lst = {1, 2, 4, 5, 6, 9, 10, 12, 15, 1000}; > The following is compiled by Mathematica: > myC = Compile[{{lst, _Integer}, {W, _Integer}}, > Module [ {i, j = 1, len = Length@lst, s, res}, > Reap[For[i = 1, i <= len, i++, > While[lst[[j]] - lst[[i]] <= W && j < len, j++]; > Sow[j - i]]; res] > ], {{res, _Integer, 4}} > ] > If Mathematica executes: myC[lst,2], it gives a message that the argument lst at position 1 should be a machine-size integer. > Can anyone help? > with friendly greetings, > P_ter > Note that it is not a good idea to use the Reap/Sow construct in a function you want to compile. Also, the local symbol 'res' has never been assigned any value before exiting the function. Having said that, I believe that the code below should do what you are looking for. (res is initialize to an empty list, then the value of j-1, when necessary, is appended to the variable res, finally the vector res is returned.) In[1]:= lst = {1, 2, 4, 5, 6, 9, 10, 12, 15, 1000}; myC = Compile[{{lst, _Integer, 1}, {W, _Integer}}, Module[{i, j = 1, len = Length@lst, res = {}}, For[i = 1, i <= len, i++, While[lst[[j]] - lst[[i]] <= W && j < len, j++]; AppendTo[res, j - i]]; res]]; myC[lst, 2] Out[3]= {2., 2., 3., 2., 1., 2., 2., 1., 1., 0.} -- Jean-Marc