Mathematica 中的符号替换问题
我想定义一个符号并在函数中使用它。例如,将 IDnumbers 定义为数字列表:
ParallelMap[{#1, Name[#1], Age[#1]} &, IDnumbers]
userlist={#1, Name[#1], Age[#1]}
变为:
ParallelMap[userlist &, IDnumbers]
它与列表本身一起工作得很好代码,但不带有符号。字符串列表与分配给字符串列表的符号也会发生同样的情况。这是为什么呢?
I want to define a symbol and use it within a function. For example, with IDnumbers defined as a list of numbers:
ParallelMap[{#1, Name[#1], Age[#1]} &, IDnumbers]
With userlist={#1, Name[#1], Age[#1]}
becomes:
ParallelMap[userlist &, IDnumbers]
It works just fine with the list itself in the code, but not with the symbol. The same thing happens with a list of strings vs. a symbol assigned to a list of strings. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
f[#]&
是Function[f[#]]
的简写,因此您应该始终使用尾随&
来完成匿名函数得到一个工作函数。在您的示例中:
更彻底的解释:
通过仅使用诸如
f[#]
之类的东西,您会得到(在FullForm[]
中),而这会被转换通过尾随
&
运算符将其转换为函数:如果分两步执行此操作,
&
不会计算中间变量expr
:您可以在包装之前强制对
expr
求值在Function[]
中使用Evaluate[]
:另一种方法是自己提供
Function[]
包装器:就我个人而言,我会考虑这样做糟糕的编码风格。只需习惯于始终使用尾随
&
来结束匿名函数,就像您为相应的左括号(
提供右括号)
一样。编辑
好的,在您动态生成的匿名函数的情况下,我可以明白为什么您不能直接提供
&
。只需将表达式与Slot[]
封装在Function[]
中即可。Since
f[#]&
is shorthand forFunction[f[#]]
you should always complete your anonymous function with a trailing&
to get a working function.In your example:
More thorough explanation:
By just using something like
f[#]
you get (inFullForm[]
)whereas this gets transformed to a Function by the trailing
&
operator:If you do this in two steps,
&
doesn't evaluate the intermediate variableexpr
:You can force the evaluation of
expr
before it gets wrapped in theFunction[]
by usingEvaluate[]
:Another way is to supply the
Function[]
wrapper yourself:Personally, i would consider this bad coding style. Just get used to always finishing an anonymous function with a trailing
&
like you would supply a closing paranthesis)
to a corresponding opening one(
.Edit
Ok, in your case of a dynamically generated anonymous function i can see why you couldn't supply the
&
directly. Just wrap the expression with theSlot[]
s in aFunction[]
instead.