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: Erik de Castro Lopo <mle+ocaml@m...>
Subject: Re: [Caml-list] Generators/iterators and lazy evaluation?
Alain Frisch wrote:

> I think you cannot implement this notion of iterator without some kind
> of control flow operator (at runtime) or some code rearrangement (at
> compile time). The point is that you must mainting several active
> "threads" of computations, including their own stack.

Alain, I think you may have misunderstood Python's yeild operator.
Typically the original poster's pow2 generators would be used like:

    for p = pow2 (10):
        print p

but I really don't see how laziness Python's generators actually
provide any benefit for this problem over the more obvious Python 
solution to this which is:

    for i = range (10):
        p = 2 ^ i
        print p

The problem with the above is that generators (and laziness in Ocaml)
really only make sense for sequences which are effecitvely infinite.
In the Python case, that would be:

    def pow2 ():
        start = 0
        yield 2^start
        start += 1

One ocaml solution to this is an class/object:

    class pow2gen =
        object
            val mutable current = 0
    
            method next () =
                current <-
                    if current == 0 then 1
                    else current * 2 ;
                current
        end

which can be used like this:

    let _ =
    	let pow2 = new pow2gen in
    	for k = 0 to 10 do
    		Printf.printf "%d : %d\n" k (pow2#next ()) ;
    		done

There would also be a lazy solution to this problem but I don't think
it would be a better solution that the object soultion above.

I've got a more realistic example of lazy lists on my blog:

    http://www.mega-nerd.com/erikd/Blog/CodeHacking/Ocaml/lazy_lists.html


Hope this helps,
Erik
-- 
+-----------------------------------------------------------+
  Erik de Castro Lopo
+-----------------------------------------------------------+
"Every time microshaft's stock price drops again, I rejoice. I
want to see that bunch of criminals brought to their knees.
Preferably at the chopping block."
-- rixt in http://linuxtoday.com/stories/20659_flat.html