MathGroup Archive 2009

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

Search the Archive

Re: Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg103789] Re: [mg103770] Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Tue, 6 Oct 2009 08:00:42 -0400 (EDT)
  • References: <200910051716.NAA10520@smc.vnet.net>

On 6 Oct 2009, at 02:16, 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 one will be a little faster. For example:

ls =  Join[RandomInteger[{-20, 20}, 10^5], RandomReal[{-20, 20}, 10^5]];

  foo /@ ls; // Timing

  {0.148462,Null}

boo /@ ls; // Timing

{0.19965,Null}

The second gives you more flexibility. For example, for any symbol,  
say a, you can define an UpValue:

IntegerQ[a] ^= True;

then

boo[a]

a^2

This can be sometimes useful.

Andrzej Kozlowski


  • Prev by Date: Re: confused about == vs === in this equality
  • Next by Date: Re: Prime/Twin Prime Generator
  • Previous by thread: Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?
  • Next by thread: Re: Which is better, foo[n_Integer] or foo[n_?IntegerQ] ?