cool

Peter Scott Peter at PSDT.com
Mon Feb 3 15:28:38 CST 2003


At 12:58 PM 2/3/03 -0800, nkuipers wrote:
>I played around in recursion a bit, wanting to get the practice but 
>also to do
>something useful.  So I framed it to myself as an exercise.  This was 
>my first
>idea:
>[snip]
>sub makeDNA {
>         my $n = shift;
>         my @alphabet = qw( A C G T);
>         if ($lengthRemaining == 0)
>         {
>                 return;
>         }
>         print $alphabet[int(rand(4))];
>         makeDNA($n - 1);
>}
>
>makeDNA(10);
>print "\n";
>
>This could develop into a small host of other recursive, random
>functionalities useful for bioinformatics, such as taking a sequence and
>randomly mutating n residues.  I will be incorporating above subroutine and
>possibly others in my BIO::Basic module.

Well, hold on a second... fun as recursion may be, it is not a 
panacea.  It is only optimal in the cases where you really do find 
yourself wanting to call the same function from within itself.  I 
suggest familiarizing yourself with a number of classic uses of 
recursion before deciding to use it.  Look for: The Tower of Hanoi, 
Ackerman's function, and anything to do with parsing a stream which may 
be lexically recursive in some fashion.

I'd write yon function above as

sub makeDNA
{
   join '' => map +(qw(A C G T))[rand 4] => 1 .. shift;
}

In general, don't print from inside utility functions.  Return strings 
instead so you can either print them or decide to do something else 
with them (e.g., run them through tests).

--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/




More information about the Victoria-pm mailing list