# Why is SparseArray atomic?

This answer tells us that functions like ReplaceAll do not straightforwardly work for the entries of sparse arrays because a SparseArray is an atomic object (though see the comments to this answer...?). As I find it a bit annoying and inelegant to have to do something like

SparseArray[ArrayRules @ # /. replacementrules, Dimensions @ #] &


when I want to use ReplaceAll on the entries of a sparse array I was wondering why one would want SparseArray (and similar functions) to be atomic in the first place: what are the benefits? In particular, if it is possible, I would like to see some practical examples of such benefits.

• 108948, Why is Graph an atomic expression in Mathematica?, are those topics exhausting this one? – Kuba Aug 22 '17 at 13:56
• It's atomic so that the internal implementation can be very efficient and can be swapped out for an even more efficient one in the future, if needed. But you are asking the wrong question. You should be asking: why doesn't ReplaceAll support sparse arrays directly? In principle there is nothing preventing Wolfram from adding this feature. In practice, "atomic" means that there are no guarantees about which structural operations work on the type. For example, both SparseArray and Rational can be decomposed by pattern matching (try a_[b___] on them), while other atoms can't. – Szabolcs Aug 22 '17 at 14:14
• This also shows you that ReplaceAll does work on SparseArray, but it does not treat it as a list. It treats it as if it had a specific compound (i.e. non-atomic) structure (that describes a compressed sparse row format). We are exploiting this in MATLink to retrieve the internal structure of sparse arrays and efficiently transfer them to/from MATLAB. – Szabolcs Aug 22 '17 at 14:16
• I think that if we start thinking about how ReplaceAll could work on a SparseArray and treat it as a list, it won't be hard to notice a number of difficulties ... for example, what would you expect 0 :> RandomReal[] to do when 0 is the background value? Replace each array element that is 0 separately, even though they are not explicitly stored? Replace the backgound value once? What if some of the explicit values are equal to the background value? – Szabolcs Aug 22 '17 at 14:22
• @JulesLamers no :) the key is 'internal'. – Kuba Aug 22 '17 at 15:27