Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Default and head in function argument

  • To: mathgroup at smc.vnet.net
  • Subject: [mg111625] Re: Default and head in function argument
  • From: "David Park" <djmpark at comcast.net>
  • Date: Sun, 8 Aug 2010 07:19:59 -0400 (EDT)

f[x : (_Integer?Positive) : 3] := x^3 

{f[3], f[], f[3.1], f[-3]} 

{27, 27, f[3.1], f[-3]} 

The parentheses in the definition are necessary.

Here is a somewhat more complicated case with two default arguments. The
first one has alternatives. As long as Mathematica can distinguish the
conditions you can omit either of the two arguments, or both of them.

g[x : (_Integer?Positive | Sqrt[2]) : 3, 
  y : (_Integer?(# <= 0 &)) : 0] := {x, y} 

{g[], g[4], g[Sqrt[2]], g[-2], g[.5, -2], g[3, -1/2], g[-1, 3]} 

{{3, 0}, {4, 0}, {Sqrt[2], 0}, {3, -2}, g[0.5, -2], g[3, -(1/2)], 
 g[-1, 3]} 


David Park
djmpark at comcast.net
http://home.comcast.net/~djmpark/  


From: NP [mailto:nomplume69 at gmail.com] 


Hi,

I know how to define a function so that it evaluates only when the
head of the argument is of a certain type:

Clear[f];
f[x_Integer?Positive] := x^3
f[3]
f[3.1]
f[-3]

27
f[3.1]
f[-3]

and I also know how to set default to an argument of a function like
so:

Clear[f]
f[x_:3]
f[]

27

How do I do both i.e., specify head and default value?

Thanks,

NP




  • Prev by Date: Re: Suggestions
  • Next by Date: Re: assuming certain properties about variables
  • Previous by thread: Re: Default and head in function argument
  • Next by thread: Re: Default and head in function argument