Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Smoothsort

by Tux (Abbot)
on Sep 21, 2015 at 09:45 UTC ( #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
Node Status?
node history
Node Type: note [id://1142614]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2020-11-24 13:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?