Re: Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?
- To: mathgroup at smc.vnet.net
- Subject: [mg103812] Re: Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Wed, 7 Oct 2009 07:02:47 -0400 (EDT)
- References: <firstname.lastname@example.org>
Nasser Abbasi wrote: > I am trying to improve some code I wrote by making the function definition > more clear by setting restriction on the parameters. > > I noticed that I could write the following > > foo[n_Integer] := n^2 > boo[n_?IntegerQ] := n^2 > > Both the above mean the same thing to me. i.e. the function is defined to > take only integer argument. > > Is one better to use? or any one is just as good? (the first uses 2 less > characters!) > > thank you, > --Nasser > > > > > The first is neater and undoubtedly more efficient (although that would only be noticeable if you called it many times). The second form is useful for tests in general, such as: boo[n_?EvenQ]:=n^2; David Bailey http://www.dbaileyconsultancy.co.uk