ExpandCollapseNext Index

+ 1.1 Generators and for loops

A special case for generators is that they can be used to create a stream of calculated values to use in the loop. For example you can generate a Fibonacci series as a generator like this:

  gen fib(count:int)():opt[int] = {
      if count > 0 do
          var a = 0;
          yield Some a;
          if count > 1 do
              var b = 1;
              yield Some b;
              for var n in 2 upto count do
                 val c = a+b;
                 yield Some c;
                 a = b;
                 b = c;
              done
          done
      done
      return None[int]; 
  }
  for n in fib(5) do
      if n != 0 do print ", "; done 
      print(n);
  done // Print 0, 1, 1, 2, 3, 5
  endl;