MathGroup Archive 2009

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

Search the Archive

Re: Map and functional constructs to replace iterative statements

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96843] Re: Map and functional constructs to replace iterative statements
  • From: Raffy <raffy at mac.com>
  • Date: Thu, 26 Feb 2009 07:53:23 -0500 (EST)
  • References: <go31ba$f47$1@smc.vnet.net>

Here is a quick tutorial for 3 common commands: /@ (Map), @@@ (Apply),
and MapThread

f /@ {a, b, c} => { f[a], f[b], f[c] } => Map[f, {a, b, c}, {1}]

f @@@ { {a, 1}, {b, 2}, {c, 3} } => { f[a, 1], f[b, 2], f[c, 3] } =>
Apply[f, {...}, {2}]
MapThread[f, { {a, b, c}, {1, 2, 3} }] => { f[a,1], f[b, 2], f[c, 3]}
=== f @@@ Transpose[ { {a, b, c}, {1, 2, 3} } ]

Map is like replacing a value x with f(x).  f /@ { a, {1, 2} } => { f
[a], f[{1, 2}] }

@@@ replaces all the heads at level 2 with f.  A matrix, List[List
[1,2], List[3,4]] becomes List[ f[1,2], f[3,4] ]

Using anonymous functions with Map, @@@, and MapThread

MapThread lets you build a list of length n, from other lists of
length n, where each element calls f as:
f[ element of first list, element of second list .... ] => f[#1,
#2, ...]

When you these commands with anonymous functions, you can write very
concise code.

MapThread[ If[#1>#2, #3 > #2, #3 <= 2]&, { {1,2}, {3,4}, {5, 6} } ]

Print[#1," = ",#2]& @@@ { {"A", 2}, {"B", 3}, {"D", 4} };

{Length[#], Total[#]} /@ { {}, {1, 3}, {9, 4, 5, 2} }


  • Prev by Date: Galois resolvent
  • Next by Date: Re: Counting Categories
  • Previous by thread: Re: Map and functional constructs to replace iterative statements
  • Next by thread: Re: Map and functional constructs to replace iterative statements