1
$\begingroup$

Consider the following:

Quit[]
Thread[g[{1, 2}, 3]]
(* {g[1, 3], g[2, 3]} *)

Thread[g[{}, 3]]
(* {} *)

This works similarly if instead $g$ takes only one parameter. Now look at the following:

Quit[]
f1[x_] := x+3;
f2[x_,y_] := x + y + {1,0};

Thread[f1[{1,2}]]
(* {4, 5} *)
Thread[f1[{}]]
(* {} *)

Thread[f2[{1,2},5]]
(* {7, 7} *)
Thread[f2[{},5]]
(* Thread::tdlen: Objects of unequal length in {}+5+{1,0} cannot be combined. *)
(* Thread::tdlen: Objects of unequal length in 5+{}+{1,0} cannot be combined. *)
(* 5 + {} + {1, 0} *)

All of these make sense except for the last one. If threading works on $f1$ with an empty list, why shouldn't it work on $f2$ with an empty list?

(BTW, there was no tag for threading.)

$\endgroup$
  • $\begingroup$ Related (possibly duplicate): (4390), (135909) $\endgroup$ – Mr.Wizard Feb 7 '17 at 21:52
  • 1
    $\begingroup$ one fix is to define f2 so that it can not accept a list as an argument , eg f2[x_?AtomQ, y_] := x + y + {1, 0} $\endgroup$ – george2079 Feb 7 '17 at 21:59
2
$\begingroup$

The message you see does not come from Thread but instead from the failed application of the Listable Attribute of Plus.

f2[{}, 5];

Thread::tdlen: Objects of unequal length in {}+5+{1,0} cannot be combined. >>

Listable does not work over empty lists in the way that Thread does, despite the message name being Thread::tdlen:

Attributes[foo] = Listable;

foo[{}, {1, 2, 3}]

Thread::tdlen: Objects of unequal length in foo[{},{1,2,3}] cannot be combined. >>

foo[{}, {1, 2, 3}]

If you want Thread to work in the example you give you'll need to control evaluation, e.g.

Thread[Unevaluated @ f2[{}, 5]]
{}
$\endgroup$
  • $\begingroup$ OK, but if $g$ is undefined, Thread doesn't even invoke $g$ when handed an empty list (or so it looks to me). $\endgroup$ – rogerl Feb 7 '17 at 21:47
  • $\begingroup$ @rogerl It's an evaluation thing; I added one more example that I hope is enlightening? Thread[g[{}, 3]] works precisely because g is undefined, i.e. it does not evaluate before Thread sees it. $\endgroup$ – Mr.Wizard Feb 7 '17 at 21:48
  • $\begingroup$ Well, I see that using Unevaluated works, but I really don't see why. I kind of assumed that the argument to Thread was unevaluated anyway, since Thread needs to pick the expression apart. $\endgroup$ – rogerl Feb 7 '17 at 21:51
  • $\begingroup$ @rogerl Please see the Related links (or now the Linked sidebar) I just added above. I believe your questions will be answered therein. If not feel free to ask more. :-) $\endgroup$ – Mr.Wizard Feb 7 '17 at 21:53
  • $\begingroup$ OK, thanks. Feel free to close as duplicate if you think it is. Sorry I didn't find them myself. $\endgroup$ – rogerl Feb 7 '17 at 21:54

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.