https://github.com/aengelberg/clj-generators

My all-time favorite feature of Python is "generators." It allows you to 
write lazy sequences imperatively.

def infinite_range():
    x = 1
    while True:
        yield x
        x += 1
for i in infinite_range():
    if (i > 5):
        break
    else:
        print(i)
=> 1 2 3 4 5

This feature is so amazing and powerful, a common practice of mine is to 
ponder how to implement such magic in other languages. Python implements 
this feature using virtual stacks to suspend the computation in memory. 
Most languages don't have a similar way to "pause" a computation like that, 
short of manipulating entire threads, which gets messy quickly. However, 
when core.async came out for Clojure, I realized that the go-blocks can in 
fact "pause" in a lightweight way (because they "park" as they read/write), 
so it came to mind as a possible candidate for a Python generator 
implementation. The infinite_range example above would translate to the 
following Clojure code:

(defn infinite-range []
  (generator
    (loop [x 1]
      (yield x)
      (recur (inc x)))))

(take 5 (infinite-range))
=> (1 2 3 4 5)

I realize this is a bit more imperative than most Clojure programmers would 
like. However, the addition of generators allows functional macros like 
"loop" to create lazy sequences (like in the example above), which it 
previously was unable to do.

Check out the github site <https://github.com/aengelberg/clj-generators> 
for more details. It's relatively slow and inefficient but serves as a 
proof-of-concept. Enjoy!

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to