Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Smoothsort

by Tux (Canon)
on Sep 21, 2015 at 09:45 UTC ( [id://1142614]=note: print w/replies, xml ) Need Help??


in reply to Smoothsort

There shall be no else after return/die/croak. Ever!

sub leonardo{ my $n = shift; if($n == 0 || $n == 1){ return 1; } else{ return leonardo($n-2)+leonardo($n-1)+1; } }

SHould be rewritten to either

sub leonardo { my $n = shift; $n == 0 || $n == 1 and return 1; return leonardo ($n - 2) + leonardo ($n - 1) + 1; }

or using a ternary

sub leonardo { my $n = shift; $n == 0 || $n == 1 ? 1 : leonardo ($n - 2) + leonardo ($n - 1) + 1 +; }

with your personal preference to whitespace and indentation of course.

The else in an if is there to give alternative code in a control flow where the code after the if/else contruct is executed for both branches. As the if branch ends with a return statement, immediatly exiting the routine, the code after if/else is never executed and only written for the else branch making the code harder to read and maintain.


Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: Smoothsort
by QuillMeantTen (Friar) on Sep 21, 2015 at 09:55 UTC

    The ternary is really so much more elegant, thanks :D

Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 09:54 UTC
    ha
    sub leonardo { return 1 if 0==$n or 1==$n; return leonardo ($n - 2) + leonardo ($n - 1) + 1; }
Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 13:15 UTC
    sub leonardo { my $n = shift; $n <= 1 || leonardo ($n - 2) + leonardo ($n - 1) + 1 +; }
Re^2: Smoothsort
by Anonymous Monk on Sep 21, 2015 at 09:52 UTC

    There shall be no else after return/die/croak. Ever!

    sure there shall for it is allowed

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1142614]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (9)
As of 2024-04-23 07:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found