13
$\begingroup$

The following is a list of attributes for the Set function:

Attributes[Set]
{HoldFirst, Protected, SequenceHold}

Why is Listable not included?

$\endgroup$
  • 12
    $\begingroup$ Would a=Evaluate@Range@5 not make 5 assignments leaving you with a==5? $\endgroup$ – Kuba Dec 5 '17 at 23:48
  • 3
    $\begingroup$ That's a good question since {a,b}={1,2} sets both a and b (and not {a,b} to {1,2} since {a,b} is not a symbol. $\endgroup$ – Henrik Schumacher Dec 6 '17 at 0:47
16
$\begingroup$

Listable is not included because Set is not Listable, imagine what would happen:

foo // Attributes = {Listable};

foo[a, {1, 2, 3, 4, 5}]
{foo[a, 1], foo[a, 2], foo[a, 3], foo[a, 4], foo[a, 5]}

That would be unexpected for Set. Five assignments instead of one and we end up with a == 5.

Why does {a,b}={1,2} work then?

Syntactic sugar. Lists are everywhere and many functions are overloaded so that one does not need to use e.g. Map or MapThread in order to perform common procedure.

You can face it on every corner:

StringMatchQ["a"] @ CharacterRange["a", "e"]
{True, False, False, False, False}
$\endgroup$
5
$\begingroup$

The key oversight is that the Listable attribute does not only allow the upgrading of arguments to equal length lists, as in:

SetAttributes[f, Listable]
f[{a, b}, {c, d}] == {f[a, c], f[b, d]}

True

But also that (from the documentation for Listable):

Arguments that are not lists are copied as many times as there are elements in the lists.

So that:

f[a, {p, q}] == {f[a, p], f[a, q]}    

True

It is this property that allows you to see clearly why Set is not listable (thanks to the comment and accepted answer from Kuba).

Say you want to assign a list to a variable, as in:

a={1,2,3}

The internal form of this is:

Set[a,{1,2,3}]

If Set had the Listable attribute, this would interpreted as:

{Set[a,1],Set[a,2],Set[a,3]}

Resulting only in the assignment a==3.

$\endgroup$

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.