Hi,

I was reading Higher Order Perl[1] last night and, dishearteningly,
got stuck on chapter one.

Mark Dominus offers the following as a  binary string conversion
example of how recursion can work.


use strict;
use warnings;

my $bstr = binary(37);
print "$bstr\n";                 # prints 100101

sub binary {
 my ($n) = @_;
 return $n if $n == 0 || $n == 1;
 my $k = int($n/2);
 my $b = $n % 2;
 my $E = binary($k);
 return $E . $b;
}


The algorithm works perfectly but my understanding of it's workings is amiss.

When I look at this I see $E initialised and then concatenate with the
the modulus of
37 % 2 =1
18 % 2 = 0
9 % 2 = 1
4 % 2 = 0
2 % 2 = 0

That by my reckoning is 10100. Almost the reverse of the answer but I
am obviously wrong and I can't see how the final expressions:

my $E = binary($k);
return $E . $b;

work to give the answer.

Can someone more enlightened than me give me some guidence.
Thanx,
Dp.


PS: Has anybody heard from Rob Dixon, he hasn't been on the list for ages.

1.  http://hop.perl.plover.com/book

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to