Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re^2: fibonacci numbers using subroutine?

by moritz (Cardinal)
on Aug 20, 2010 at 08:37 UTC ( #856208=note: print w/replies, xml ) Need Help??

in reply to Re: fibonacci numbers using subroutine?
in thread fibonacci numbers using subroutine?

Just to show off, here's a Perl 6 solution:

sub MAIN($limit as Int) { say (0, 1, *+* ... *)[$limit]; }

Which you call as

perl6 8

To obtain the 8th fibonacci number.

As an explanation, MAIN takes its arguments from the command line, and is run automatically at startup. as Int converts the command line argument (which is a string) to an integer (this is not sctrictly necessary). 0, 1, *+* ... * is a lazy, infinite list starting with 0 and 1, and then is built by summing the two previous elements. [$limit] takes the $limit's element of that list, with a zero-based index. (Which is why the fibonacci sequence starts with 0, 1 instead of 1, 1 in that program).

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^3: fibonacci numbers using subroutine?
by TimToady (Parson) on Aug 20, 2010 at 18:33 UTC
    In practice, though, if you're going to reuse a series in your Perl 6 program, you'll want to memoize the series by binding the series to an array, like this:
    my @fib := (0,1, *+* ... *); say @fib[8]; say @fib[9]; # doesn't recalculate fib(8)
    Both lists and arrays can be lazily infinite in Perl 6; the only real difference is whether the values are kept in an indexable form as they are generated. Note also that the memoization naturally uses an array rather than a hash in this case, which saves memory over those memoization techniques that must assume a hash for generality.
Re^3: fibonacci numbers using subroutine?
by JavaFan (Canon) on Aug 20, 2010 at 09:11 UTC
    Wait. Perl6 doesn't have OEIS() as a primitive? I can't just do OEIS(45)[8].say?
      No, but we do have a module system that allows you to write that.

      See a small guide for module authors if you feel like contributing - it would certainly be appreciated.

      Perl 6 - links to (nearly) everything that is Perl 6.
        Well, I can easily write such a module in Perl. For now, I've no interest in Perl6, so I'll spend my time on Perl instead.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2023-05-28 17:35 GMT
Find Nodes?
    Voting Booth?

    No recent polls found