On 09/12/2011 01:36 PM, bearophile wrote:
It seems people (Andrei too) are slowly adding more comments in that Reddit 
thread.
A sub-thread:
http://www.reddit.com/r/programming/comments/kaxjq/the_d_programming_language_is_back_in_tiobes_top/c2iycwb

It starts with this question:

How would you write this kind of Python in D?

from struct import Struct
def decode(buf):
     while buf:
         s = Struct(buf[0])
         val, = s.unpack(buf[1 : 1 + s.size])
         yield val
         buf = buf[1 + s.size:]

Or this:

def powerset(items):
     if not items:
         yield []
         return
     item, rest = items[0], items[1:]
     for opt in [[item], []]:
         for r in powerset(rest):
             yield opt + r

btw, I like Haskell even more, and in it, the latter example is:

powerset [] = return []
powerset (x:xs) = do
   o<- [[x], []]
   r<- powerset xs
   return $ o ++ r

Or, you can re-use the filterM function, and get:

powerset = filterM (\x ->  [True,False])

Equivalent D version. Runs in ca 22 min on my machine (for computing the size of P(Z_21))

LList!(List!T) powerset(T)(Lazy!(List!T) xs){
    return lz({
            if(xs().empty) return list(Empty!T)();
            auto r=lz({return powerset(xs().tail)();});
return chain(r,map((LList!T a){return cons(xs().head,a);},r))();
        });
}

writeln(powerset(take(21,naturals(0))).length);


2097152

real    21m58.438s
user    21m32.320s
sys     0m4.710s




Reply via email to