如果我想从两个列表list1和list2中找到所有可能的和,我使用Outer[]函数,并将Plus指定为组合运算符:
In[1]= list1 = {a, b}; list2 = {c, d}; Outer[Plus, list1, list2]
Out[1]= {{a + c, a + d}, {b + c, b + d}}
如果我想要处理任意数量的列表,例如一个列表的列表,
In[2]= listOfLists={list1, list2};
那么我知道如何找到所有可能的总和的唯一方法是使用Apply[]函数(它有简写@@)以及Join:
In[3]= argumentsToPass=Join[{Plus},listOfLists]
Out[3]= {Plus, {a, b}, {c, d}}
In[4]= Outer @@ argumentsToPass
Out[4]= {{a + c, a + d}, {b + c, b + d}}
或者只需
In[5]= Outer @@ Join[{Plus},listOfLists]
Out[5]= {{a + c, a + d}, {b + c, b + d}}
问题在于当我尝试编译时:
In[6]= Compile[ ..... Outer @@ Join[{Plus},listOfLists] .... ]
Compile::cpapot: "Compilation of Outer@@Join[{Plus},listOfLists]] is not supported for the function argument Outer. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function. "
事实上,我正在使用支持的函数,即Plus。问题似乎仅与Apply[]函数有关。因为如果我给它一个固定数量的列表来outer-plus,它就可以正常工作
In[7]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer[Plus, bob, joe]]
Out[7]= CompiledFunction[{bob, joe}, Outer[Plus, bob, joe],-CompiledCode-]
但是一旦我使用Apply,它就会出错
In[8]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer @@ Join[{Plus}, {bob, joe}]]
In[1]= list1 = {a, b}; list2 = {c, d}; Outer[Plus, list1, list2]
Out[1]= {{a + c, a + d}, {b + c, b + d}}
如果我想要处理任意数量的列表,例如一个列表的列表,
In[2]= listOfLists={list1, list2};
那么我知道如何找到所有可能的总和的唯一方法是使用Apply[]函数(它有简写@@)以及Join:
In[3]= argumentsToPass=Join[{Plus},listOfLists]
Out[3]= {Plus, {a, b}, {c, d}}
In[4]= Outer @@ argumentsToPass
Out[4]= {{a + c, a + d}, {b + c, b + d}}
或者只需
In[5]= Outer @@ Join[{Plus},listOfLists]
Out[5]= {{a + c, a + d}, {b + c, b + d}}
问题在于当我尝试编译时:
In[6]= Compile[ ..... Outer @@ Join[{Plus},listOfLists] .... ]
Compile::cpapot: "Compilation of Outer@@Join[{Plus},listOfLists]] is not supported for the function argument Outer. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function. "
事实上,我正在使用支持的函数,即Plus。问题似乎仅与Apply[]函数有关。因为如果我给它一个固定数量的列表来outer-plus,它就可以正常工作
In[7]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer[Plus, bob, joe]]
Out[7]= CompiledFunction[{bob, joe}, Outer[Plus, bob, joe],-CompiledCode-]
但是一旦我使用Apply,它就会出错
In[8]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer @@ Join[{Plus}, {bob, joe}]]
Out[8]= Compile::cpapot: "Outer@@Join[{Plus},{bob,joe}]的编译不支持函数参数Outer。唯一支持的函数参数是Times、Plus或List。评估将使用未编译的函数。"
所以我的问题是:是否有一种方法可以规避这个错误,或者在编译函数中计算从任意数量的列表中提取的所有元素的可能总和的方法?
(另外,我不确定"compilation"是否是一个合适的标签。请给予指导。)
非常感谢。