I’ve been doing the Perl Weekly
Challenges. The
latest
involved fractional exponentiation and sweating with the oldies. (Note
that this is open until 28 March 2021.)
TASK #1 › Nth root
You are given positive numbers $N and $k.
Write a script to find out the $Nth root of $k. For more
information, please take a look at the wiki
page.
Well, all of my chosen languages have some sort of fractional
exponentiation capability so return $k^(1/$N)
would have been a
valid answer. But this is meant to be at least some sort of challenge,
so I implemented Newtonian iteration. In Raku:
sub nroot($n,$a) {
my $xk=2;
while (1) {
my $xk1=(($n-1)*$xk+$a/($xk ** ($n-1)))/$n;
if ($xk1==$xk) {
last;
}
$xk=$xk1;
}
return $xk;
}
and the others look basically the same. The only fiddliness was in
Rust, where there's no exponentiation operator, but rather library
function calls.
let xk1=((n-1.0)*xk+a/(xk.powf(n-1.0)))/n;
TASK #2 › The Name Game
You are given a $name.
Write a script to display the lyrics to the Shirley Ellis song The
Name Game. Please checkout the
wiki page for more
information.
I admit I didn't bother with trying to work out where syllable
stresses might lie; instead, I make a "tail" part that's the name with
any initial consonants removed. (I assume that an initial Y will be a
vowel sound, favouring Yves over Yanni; I suppose the next level of
sophistication would treat Y as a consonant if and only if a vowel
follows it.) If there was no initial consonant, drop the tail into
lower case.
Then it's a matter of interpolating name and tail into the template.
In Perl:
sub ng {
my $name=shift;
(my $tail=$name) =~ s/^[bcdfghjklmnpqrstvwxz]*//i;
if ($tail eq $name) {
$tail=lc($tail);
}
return "$name, $name, bo-b$tail\nBonana-fanna fo-f$tail\nFee fi mo-m$tail\n$name!";
}
Python has grown string interpolation in recent versions, so I didn't
have to use its special formatting language.
return f"{name}, {name}, bo-b{tail}\nBonana-fanna fo-f{tail}\nFee fi mo-m{tail}\n{name}!"
Rust is above all that sort of thing (though I do think that having to
separate the variable list from the template is prone to producing
errors, just like good old sprintf
; there is a system of named
parameters which might help but is rather verbose).
return format!("{}, {}, bo-b{}\nBonana-fanna fo-f{}\nFee fi mo-m{}\n{}!",name,name,tail,tail,tail,name);
And of course hope that none of your users is called "Buck".
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.