Wolfram mathematica 理解Mathematica中的模块参数修改
如果我在Mathematica中执行以下操作Wolfram mathematica 理解Mathematica中的模块参数修改,wolfram-mathematica,Wolfram Mathematica,如果我在Mathematica中执行以下操作 f[l_] := Module[{}, l[[1]] = Append[l[[1]], 3]; l] f[{{}, 3}] 我得到一个错误: Set::setps: "{{},3} in the part assignment is not a symbol. " 偶l={{},3};f[l]获取相同的错误。但是我可以做f[l_3;]:=Module[{},{Append[l[[1]],3],l[[2]}]或l={{},3};l[[1]]=追加[
f[l_] := Module[{}, l[[1]] = Append[l[[1]], 3]; l]
f[{{}, 3}]
我得到一个错误:
Set::setps: "{{},3} in the part assignment is not a symbol. "
偶l={{},3};f[l]
获取相同的错误。但是我可以做f[l_3;]:=Module[{},{Append[l[[1]],3],l[[2]}]
或l={{},3};l[[1]]=追加[l[[1]],3];l
你的解释是什么?试试看
f[{{}, 3}] // Trace
您可以看到,l
的值在求值之前插入到l[[1]]=Append[l[[1]],3]
位。所以mma正在尝试评估:{{},3}[[1]]={3}
这可能是你想要的
ClearAll[f];
f[l_] := Module[{},
Append[l[[1]], 3]~Join~Rest[l]
]
(想法是避免分配给代码< L>代码>的部分,因为在尝试进行赋值之前将对代码< L>代码进行评估)
如果你想在你的模块中使用一部分,你可能想考虑使用一个临时变量:f[l_List] := Module[{t = l}, t[[1]] = Pi; t]
以及:
这里有多个问题:
f[x_] := head[x, 2, 3]
类似于带有的:
With[{x = something}, head[x, 2, 3]]
也就是说,直接在求值之前进行替换,这样函数Head
甚至不会看到对象x
。看看这会发生什么:
ClearAll[f,x]
x = 5;
f[x_] := (x = x+2; x)
f[x]
{{3},3}我在我的书中详细讨论了这个话题,特别是在这里:,这里:@LeonidShifrin:噢,让我看看。谢谢你的推荐信。:)感谢您的完整和透彻的解释!
ClearAll[f,x]
x = 5;
f[x_] := (x = x+2; x)
f[x]
During evaluation of In[8]:= Set::setraw: Cannot assign to raw object 5. >>
Out[]= 5
ClearAll[f, x, incrementX]
incrementX[] := (x += 2)
x = 3;
incrementX[];
x
5
f[x_] := (incrementX[]; x)
f[x]
5
x
7
ClearAll[heldF]
SetAttributes[heldF, HoldAll]
x = {1, 2, 3};
heldF[x_] := (x[[1]] = 7; x)
heldF[x]
x
<pre>{7, 2, 3}</pre>
<pre>{7, 2, 3}</pre>
ClearAll[proxyF]
x = {1, 2, 3};
proxyF[x_] := Module[{proxy = x}, proxy[[1]] = 7; proxy]
proxyF[x]
proxyF[{1, 2, 3}]
x
{7, 2, 3}
{7, 2, 3}
{1, 2, 3}
ClearAll[directF]
x = {1, 2, 3};
directF[x_] := ReplacePart[x, 1 -> 7]
directF[x]
x
{7, 2, 3}
{1, 2, 3}
ClearAll[f]
f[l_] := ReplacePart[l, 1 :> l[[1]] ~Append~ 3]
f[{{}, 3}]
{{3}, 3}