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?
This only happens to work because
NumberFormworks on lists:gives
Map[f, {{a, b, c}}]simply mapsfontoFirst[{{a,b,c}}], namely, onto{a,b,c}; so you getf[{a,b,c}].So unfortunately adding
{}will not work in general.A simple way to do this is to define
whence
give
However this does not allow for the
Map[f,expr,levelspec]form (which however is easy enough to implement).This also works in this case: