Re: the simplest way?
- To: mathgroup at smc.vnet.net
- Subject: [mg16436] Re: the simplest way?
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Sat, 13 Mar 1999 02:21:47 -0500
- References: <7c58om$7lr@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Antoine Zahnd wrote in message <7c58om$7lr at smc.vnet.net>... >Hello, > >I have two questions with lists, each time to avoid the Length function. > > >1) For example, how to write a function that will go thru the elements of a >list of >integers, and will return False as soon as an odd number is found, without >using >Length? FreeQ[{2,4,3,2}, _?OddQ] False (Your code below gives True when an odd integer is found) > > >With Length it is easy, but not so clean ... >f[l_]:= Block[{k},For[k=1,k<=Length[l],k++,If[OddQ[l[[k]]],Return[True]]]; >False]; > > >2) Is it possible to write the following function without Length? > >l={1,2,3}; >Table[ReplacePart[l,l[[i]]-1,i],{i,1,Length[l]}] >{{0,2,3},{1,1,3},{1,2,2}} Yes, but your way is efficient - Length is very quickly found. Here are two alternatives MapIndexed[ MapAt[#-1&,l,#2]&,l] MapIndexed[ ReplacePart[l,l[[#2]]-1,#2]&,l]] >More generally, is there a way to write something like: >(for x in l ... collect (f x) ) , and the collection of the (f x) are >returned >in a list? > >I don't see how to write a Lisp style dolist function in Mathematica >without the Length! It's a long time since I used Lisp, but the functions Map, Apply, MapIndexed, Scan, Cases, DeleteCases, MapAt are generally useful for this kind of thing, especially when used with all the extra controls possible - please check in the Help Browser. --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565