The semantics of Mathematica's Thread function, someone needs to finally put this to rest

僤鯓⒐⒋嵵緔 提交于 2019-12-03 10:38:54

Thread is a bit like a generalization zip from other functional languages.

For simple cases, where all the elements of args from your example are lists,

Thread[f[args]]

is equivalent to

f @@@ Transpose[{args}]

as shown in the first couple examples in the documentation. The major wrinkle is when you have args that are not lists, in which case they're effectively curried out; for example,

Thread[g[{a, b}, c, {d, e}, f]]

is equivalent to

g[#1, c, #2, f]& @@@ Transpose[{{a, b}, {d, e}}]

I usually find myself using Thread to construct lists of rules or lists of equations.

It works similarly to Python's zip() function, but in a slightly more general fashion. For example:

In[1] := Thread[{{1, 2, 3}, {4, 5, 6}}]  (* f == List *)
Out[1] = {{1, 4}, {2, 5}, {3, 6}}

In[2] := Thread[f[{1, 2, 3}, {4, 5, 6}]]
Out[2] = {f[1, 4], f[2, 5], f[3, 6]}

In[3] := Thread[f[a+b+c, d+e+f], Plus]
Out[3] = f[a, d] + f[b, e] + f[c, f]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!