[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: list-based queues



Pretty code; here's an even shorter version.

Queue: adt {
	h: list of string; 
	t: list of string;
	put: fn(q: self ref Queue, s: string);
	get: fn(q: self ref Queue): string;
	new: fn(): ref Queue;
};

# This function is really unnecessary, as this shorter version should make
clear.
Queue.new(): ref Queue
{
	return ref Queue;
}

Queue.put(q: self ref Queue, s: string)
{
	q.t = s :: q.t;
}

Queue.remove(q: self ref Queue): string
{
	s := "";
	if(q.h == nil){
		q.h = revlist(q.t);
		q.t = nil;
	}
	if(q.h != nil){
		s = hd q.h;
		q.h = tl q.h;
	}
	return s;
}

# or inline
revlist(ls: list of string) : list of string
{
	rs: list of string;
	while(ls != nil){
		rs = hd ls :: rs;
		ls = tl ls;
	}
	return rs;
}