3 ms·
Here's a (rough) Python equivalent: from itertools import islice def fib(): a, b = 0, 1 while True: yield a a, b = b, a +
by jparise 16y ago
Here's a (rough) Python equivalent:
from itertools import islice
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
for k in islice(fib(), 1, 100):
print(k)
It uses a generator function to produce an infinite iterable sequence. islice() is used to produce just a slice of that sequence.
This could probably be written using fewer characters, but I don't think it could be anywhere near a short (and terse) as the Perl version.
- masak 16y agoCorrect me if I'm wrong, but that code prints 100 fibonacci numbers, whereas the Perl 6 code prints all fibonacci numbers up to, but not including, 100.
- jparise 16y agoYou're right. I misread the range of the Perl version. Adjust the slice accordingly.
- masak 16y agoNo, that's too easy a cop-out. :-) How would you stop at the right number in Python code? Would you compute 100 numbers and then inspect/truncate afterwards?
- jparise 16y agoAh, I see that I truly missed your earlier point. I suppose I would just do this: def fib(max): a, b = 0, 1 while a < max: yield a a, b = b, a + b for k in fib(100): print(k)
- joeyh 16y agoAnd a haskell version (not the shortest possible one): takeWhile (< 100) fibs where fibs = 0 : 1 : zipWith (+) fibs $ tail fibs I don't think fibs can be expressed as a list comprehension in haskell, can it? It's cute that perl6 is able to use one, but OTOH I can't think of many other lists I'd want to use that trick to calculate. And, despite having written perl for 15 years, I find the haskell version much clearer, and its use of laziness and infinite lists (zipping them up in particular) much more advanced than perl6's.