For example consider the following function:
Function[{u,v},u^2+v^4]
Is there anyway to define default values for the variables u
and v
?
I know that this is possible for ordinary functions as follows:
f[u_:1,v_:0]:=u^2+v^4
But I am looking for a way to do this with pure functions defined by Function[]
.
Answer
As far as I know there is no way to do this with the named parameter form of Function
but you can use destructuring methods with SlotSequence
(##
):
f = {##} /. {u_: 1, v_: 0} :> body[u, v] &;
f[]
f[7]
f[7, 8]
body[1, 0]
body[7, 0]
body[7, 8]
It is possible to give your pure function Attributes
using an undocumented form.
For Hold attributes you could use Hold
or HoldComplete
:
g = Function[Null, Hold[##] /. _[u_: 1, v_: 0] :> HoldForm[{u, v}], HoldAll];
g[1 + 1]
{1 + 1, 0}
Comments
Post a Comment