I have been learning to use Map more (to become more functional programmer). It looks like Map wants a list as the expression to apply the function to. If the expression is not a list, then it is not happy.
I use NumberForm in this example to illustrate what I mean:
I can Map NumberForm on the whole list ok:
data = {1, 2, 3}
Map[NumberForm[#, {3, 2}] &, data]
But if I try to Map it to some specific element in the list, say the first one in the above, it does not work
data = {1, 2, 3}
Map[NumberForm[#, {3, 2}] &, data[[1]] ]
The result returned is NOT formatted. Same as original data. i.e I get back '1' and not '1.00' as in the other examples.
To solve, I added extra {}
data = {1, 2, 3}
Map[NumberForm[#, {3, 2}] &, {data[[1]]} ]
it works now, (just need to remove the {} from the result using First).
So I thought, then why not add this extra {} all the time and remove it in the end?
This way, I do not have to worry if what I am Map'ing function to happened to be not a list like in the above example?
So, my examples will all becomes like this:
data = {1, 2, 3}
First@Map[NumberForm[#, {3, 2}] &, { data } ]
First@Map[NumberForm[#, {3, 2}] &, { data[[1]] } ]
This way, code will works on everything and I do not have to make special check before using Map if what I happened to be applying Map to is a list or not.
Question is: Does the the above look an OK solution for the experts, or is there a better way to handle this?
Mapon to something which is not a list? - David ZMapon something else than a list, but this is rather rare and anyways done in situations different from the one discussed in this question. A typical example would be something likeMap[f, myContainerA[myContainerB[1, 2, 3], myContainerC[4, 5, 6]], {2}], although in cases like that I usually use rules. - Leonid Shifrinmapfunction he shows, just as I said for my use of levelspec{-1}. If you usemap[f, Sqrt[2]]you will see that this may not be what you want. I still believe there is a deeper issue of method implicit in your question that has not been well addressed. - Mr.Wizardmapor myMap[f, x, {-1}]. Would you please consider adding some use context to your question, that we may better recommend an approach? - Mr.Wizard