Every time control is called, it resets itself to “resume”, which is next expression to be executed.

Next step, we rewrite control function to take numbers from a list. It is done by adding for-each and a lambda function to consume every number in the list:

#lang scheme (define (consume) (call/cc control)) (define (control ret) (for-each (lambda (elem) (call/cc (lambda (resume) (set! control resume) (ret elem)))) '(1 2 3)))

Finally, we put both consume and control functions inside a function itor. We take a list as parameter, instead of hard coded input.

#lang scheme (define (itor lst) (define (consume) (call/cc control)) (define (control ret) (for-each (lambda (elem) (call/cc (lambda (resume) (set! control resume) (ret elem)))) lst)) consume) (define consume (itor '(a b c))) (consume) (consume)]]>

Consider the insertion on a sorted linked list:

void ins(node **l, int x) { node **p = l; while (*p && (*p)->data <= x) p = &((*p)->next); *p = new node(x, *p); }]]>

Python is not a lazy programming language but we can simulate this behavior using generator.

def int2(): x = 2 while True: yield x x = x + 1

int2 is a generater that produces all integers greater than 1.

def filter(gen): x = gen.next() #take the first element yield x while True: y = gen.next() if y % x != 0: yield y

filter takes a generator as input, and converts it into another generator by filtering out any number that is multiplier of the first element of the input generator.

def seive(): g = filter(int2()) while True: yield g.next() g = filter(g) prime = seive()

Here prime is a generator that conceptually contains all prime numbers! Let us take first 10 from it:

for x in xrange(0, 10): print prime.next()]]>

http://terrytao.wordpress.com/2011/04/07/the-blue-eyed-islanders-puzzle-repost/

]]>

**Writer:**

new_wptr = wptr + 1;

if (cas (c, wptr, new_wptr) == 0) {

//c is NULL, which implies reader is sleeping or is going to sleep

wptr = new_wptr;

//reader is sleeping or is going to sleep, so it is safe to update c

c.set(new_wptr);

return WAKEUP;

}

//c is new_wptr now

wptr = new_wptr;

return DONOT_WAKEUP;

**Reader:**

if (cas (c, rptr, 0) == rptr)

return SLEEP;

++rptr;

return DONOT_SLEEP;

mailbox is the inter-thread communication mechanism . In 0mq, whenever one thread wants to modify the status of the other one, it sends a message to inform the other thread to do it. You don’t need any synchronization among threads since they don’t share anything.

mailbox is implemented using sock_pair. The data type communicated through the sock_pair is defined as command_t (command.h/cpp). Other than the message type and message parameters, one import component of every message is the “destination”, which is an interferce type defined as “object_t” (object.cpp/h). object_t has a function process_command(command_t& cmd), for different message type, a different virtual function will be called to response the message type.

In current 0mq, every iothread object and every socket own a mailbox.

One important command for 0mq socket is “Activiate”. A thread calling blocking read on an empty pipe will be blocked by calling process_command (block on reading sock_pair); Later on, a writer thread to the pipe will send an “Activate” command to wake it up. The lockless pipe of 0mq adopts an interesting design: The writer can know exactly if the reader is blocked or is going to be blocked, so it only does notification when necessary — This greatly improves the performance.

]]>int i=0, j=0, size=static_cast<int>(n), k;

while(i<n && j<size) {

for(k=0; k<size && s[(i+k)%size]==t[(j+k)%size]; ++k);

if(k==size) return true;

if(s[(i+k)%size]>t[(j+k)%size])

i+=k+1;

else

j+=k+1;

}

return false;

}

Given two strings and , this function returns true if and only if and are equivalent under circular shift. and are equivalent under circular shift if there is an index such that for any integer , .

It is easy to see that the worst case running time of this function is linear: The asymptotic running time is bounded by the total number of iterations executed by the inner “for” loop. In each iteration, the value of will be increased and ultimately, the increment will be accumulated into either variable or . When either or reaches , the function will return.

Why do I post this small piece of program? It is a perfect example to show a program can be short but still not easy to understand. It is also one of my favorite examples to convince people “loop invariant proof” is a good way to understand a program — if it is not the only way. You may load the program into your favorite debugger, and check closely how each single line is executed; you may feed it with all kind testing cases, and verify every output. But you simply cannot get enough insight to convince yourself why the program is correct. This is what I believe in: *Program should be proven to be correct; Testing should only be used to catch typos.*

How to prove this program is correct? Let us introduce several notations first.

**1.** Given string of length of , define .

**2.** Define . That is, the set of strings generated by shifting .

**3.** For a string and a set of strings , we call *beats * if there is a string such that .

4. For two set of strings and , we call *beats * if for any string , there exists a string such that .

**Claim**: and are equivalent if and only if neither beats nor beats . (Hints: If and are equivalent, then . So the minimum string in cannot beat vice versa.)

Our program holds such invariant: At the beginning of each iteration of the “while” loop, for any , beats ; for any , beats . We will skip the proof of the invariant since it is trivial. With this invariant, when the while loop stops we have either:

1. k==size: in this case, the two string are equivalent. (return true)

2. i>=size or j>=size: in this case, either beats or beats , so and are not equivalent by the claim. (return false)

P.S. The function returns false for empty strings () and one may argue that true should be returned instead.

]]>