Version française
Home     About     Download     Resources     Contact us    
Browse thread
Generators/iterators and lazy evaluation?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Raj B <rajb@r...>
Subject: Generators/iterators and lazy evaluation?
Hi all

I've been using OCaml for a year or so building an interpreter/ 
compiler for the Python programming language as a research project.

It's worked pretty well for most part, but I'm trying to implement  
some of the features of Python involving 'lazy' features, such as  
generator functions and list comprehensions.

A generator in Python can be thought of as an arbitrarily generated  
'lazy list'. As an example
the following is a generator capable of generating powers of 2 upto a  
max value.

def pow2(max):
    start = 0
    while (start .lt. max):
       yield 2^start
       start += 1

The 'yield' statement is the point where the function returns the  
next value and suspends itself until the next time it is 'forced'. At  
that time it resumes execution where it left off.

OCaml makes this particularly hard to implement this due to lack of  
'control flow' features, including even a call/cc. The only way I can  
see right now is breaking this code down into little functions,  
saving the current execution environment during the suspend and  
keeping track of the right function to call the next time.

I've been thinking about whether I can express this in some elegant  
way in some lazy construct in OCaml, since this is basically a form  
of 'lazy' evaluation. However, I come from the C world and am not  
quite used to 'lazy' thinking :) Any ideas?

Thanks in advance
Raj

--

The Python charmer

           _                   .-=-.          .-==-.
        { }      __        .' O o '.       /  -<' )
        { }    .' O'.     / o .-. O \     /  .--v`
        { }   / .-. o\   /O  /   \  o\   /O /
         \ `-` /   \ O`-'o  /     \  O`-`o /
     jgs  `-.-`     '.____.'       `.____.'