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

标签 wolfram-mathematica symbols substitution

我想定义一个符号并在函数中使用它。例如,将 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/

相关文章:

c# - 读写8位以上的符号

r - 您可以使用 Replace() 从文本字符串在 R 中创建函数吗?

Linux Sed 在替换期间添加新行

wolfram-mathematica - Mathematica 中 Flatten 的倒数?

wolfram-mathematica - 对 Manipulate 语句中的表达式求值

image-processing - Mathematica 编程图形

debugging - Microsoft Windows 调试工具中的符号?

wolfram-mathematica - 关于 "smart"在 mathematica 中替换的问题

c++ - 无法在 Visual Studio 2010 中加载 libcef 符号

linux - 在 sed 脚本中使用带有参数的命令替换