update page now

Voting

: min(two, five)?
(Example: nine)

The Note You're Voting On

Geoffrey Sneddon
16 years ago
So, playing around with iterators in PHP (coming from languages where I'm spoiled with generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to infinity, though only the first terms up to F_{10} are output).
<?php
class Fibonacci implements Iterator {
 private $previous = 1;
 private $current = 0;
 private $key = 0;
 
 public function current() {
 return $this->current;
 }
 
 public function key() {
 return $this->key;
 }
 
 public function next() {
 $newprevious = $this->current;
 $this->current += $this->previous;
 $this->previous = $newprevious;
 $this->key++;
 }
 
 public function rewind() {
 $this->previous = 1;
 $this->current = 0;
 $this->key = 0;
 }
 
 public function valid() {
 return true;
 }
}
$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
 echo "$f\n";
 if ($i++ === 10) break;
}
?>

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /