The Pure Function tutorial gives an example: Map[Function[x, x^2], a + b + c].

I would expect the output to be (a + b + c)^2, but instead it returns a^2 + b^2 + c^2. Map[Function[x,x^2],a+b+c]//FullForm even gives Plus[Power[a,2],Power[b,2],Power[c,2]] which provides no clarity. What's going on here?


Its not the pure function you trip over, it's the property of Map : it not only maps into elements of a list, but just as well into Plus or Times or into the function with head travis (pardon my pun).
Map[z, travis[a, b, c]] gives (* travis[z[a],z[b],z[c]] *)

|improve this answer|||||
  • $\begingroup$ Whoa, trippy! Map[#+1&,f[A[x]+B[x]]+g[A[x]+B[x]],2] $\to$ 2+f[1+A[x]+B[x]]+g[1+A[x]+B[x]]. Why didn't I end up with 2+A[x]+B[x] inside f and g? It mapped into the Plus[f,g] twice (once for f and once for g), but it only mapped into the Plus[A,B] at level two once? For which one, A or B? $\endgroup$ – Travis Bemrose Apr 14 '14 at 10:14
  • $\begingroup$ You can use FullForm[exp] to see what the heads are at every level of an expression. If you want map to work only at the specified level, lev you need to use curly brackets: Map[f,expr,{lev}]. If you omit them, Map will map at every level up to lev. $\endgroup$ – gpap Apr 14 '14 at 10:20
  • $\begingroup$ Weird, Map[...,...,3] gives 3+A[x]+B[x]. I guess I know what help page I'm reading next. $\endgroup$ – Travis Bemrose Apr 14 '14 at 10:21
  • $\begingroup$ @gpap I understood (yeah right) that Map would map into every level up to lev, but if I'm following the levels right, in my comment above, it didn't map into the second level the same way it mapped into the first level. Mapping into Plus[f,g] gave 2+f+g. Mapping into Plus[A,B] ... nevermind, f[] and g[] would be the second (and third?) level(s) wouldn't they? $\endgroup$ – Travis Bemrose Apr 14 '14 at 10:28
  • 1
    $\begingroup$ @TravisBemrose because the heads at the second level are f and g so map does f[whatever]$\rightarrow$f[1+whatever]. At the third level the head is Plus. You can replace TreeForm for my FullForm to see the level hierarchy more clearly $\endgroup$ – gpap Apr 14 '14 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.