gpt4 book ai didi

wolfram-mathematica - Mathematica 中的符号替换问题

转载 作者:行者123 更新时间:2023-12-01 18:19:23 24 4
gpt4 key购买 nike

我想定义一个符号并在函数中使用它。例如,将 IDnumbers 定义为数字列表:

ParallelMap[{#1, Name[#1], Age[#1]} &, IDnumbers]

使用 userlist={#1, Name[#1], Age[#1]} 变为:

ParallelMap[userlist &, IDnumbers]

它可以与代码中的列表本身一起正常工作,但不能与符号一起使用。字符串列表与分配给字符串列表的符号也会发生同样的情况。这是为什么?

最佳答案

由于 f[#]&Function[f[#]] 的简写,因此您应该始终使用尾随 & 来完成匿名函数> 获得工作功能。在您的示例中:

userlist={#1, Name[#1], Age[#1]}&
ParallelMap[userlist, IDnumbers]

更彻底的解释:

通过使用像 f[#] 这样的东西,你会得到(在 FullForm[] 中)

In[15]            := f[#] // FullForm
Out[15]//FullForm = f[Slot[1]]

而这会通过尾随的 & 运算符转换为函数:

In[16]            := f[#]& // FullForm
Out[16]//FullForm = Function[f[Slot[1]]]

如果分两步执行此操作,& 不会计算中间变量 expr:

In[25]:= expr = f[#]//FullForm
In[26]:= expr &
Out[25]//FullForm = f[Slot[1]]
Out[26] = expr &

您可以使用 Evaluate[] 在将 expr 包装到 Function[] 之前强制对其求值:

In[27]:= expr=f[#]//FullForm
In[28]:= Evaluate[expr]&
Out[27]//FullForm = f[Slot[1]]
Out[28] = f[Slot[1]]&

另一种方法是自己提供 Function[] 包装器:

userlist={#1, Name[#1], Age[#1]}
ParallelMap[Function[userlist], IDnumbers]

就我个人而言,我认为这种编码风格很糟糕。只需习惯于始终使用尾随 & 来结束匿名函数,就像您为相应的左括号 (.< 提供右括号 ) 一样。/p>

编辑好的,在您动态生成的匿名函数的情况下,我可以明白为什么您不能直接提供 & 。只需将表达式与 Slot[] 封装在 Function[] 中即可。

关于wolfram-mathematica - Mathematica 中的符号替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6737388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com