MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: foreach loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg51950] Re: [mg51868] foreach loop
  • From: Yasvir Tesiram <yat at omrf.ouhsc.edu>
  • Date: Fri, 5 Nov 2004 02:19:04 -0500 (EST)
  • References: <200411040649.BAA18018@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

G'day,
There are many ways of doing this in Mathematica. In fact almost every 
operation will act on each element of a list. Here are two examples of 
iterating through two lists of strings;

seasons = ToString /@ {fall, winter, spring, summer}
assocTemp = ToString /@ {cool, cold, warm, hot}

Clear[f]
f[x_, y_] := Table[x[[i]] <> " is " <> y[[i]] <> "\n", {i, 1, 
Length[x], 1}]
f[seasons, assocTemp]

Clear[f]
f[x_, y_] := #1 <> " is " <> #2 <> "\n" &
MapThread[f[x, y], {seasons, assocTemp}]

and there are many other ways.

/@ is shorthand for Map
[[]] is shorthand for Part
<> is shorthand for StringJoin
#1 is the first variable in a pure function
#2 is the second variable in the same pure function

Cheers
Yas


On Nov 4, 2004, at 12:49 AM, symbio wrote:

> Is there a foreach loop statement in Mathematica?  I need to loop 
> through a
> list of words, rather than numbers.  I need the equivalent of Do[expr,
> {n,0,10,1}], except I need to step through a list like so:  foreach 
> loop
> [expr, {fall, winter, spring, summer}].  Can anyone help?


  • Prev by Date: Re: Re: Counting Runs
  • Next by Date: Re: Functions with optional parameters
  • Previous by thread: Re: foreach loop
  • Next by thread: Re: foreach loop