123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- (library (queue)
- (export empty-queue
- enqueue
- dequeue
- queue-empty?)
- (import
- (except (rnrs base) let-values map error)
- (only (guile)
- lambda* λ)
- (ice-9 match)
-
- (srfi srfi-8))
-
- (define empty-stack '())
- (define (push stack x)
- "Push an element onto the stack by cons-ing it to the list,
- which is used as stack."
- (cons x stack))
- (define (pop stack)
- "Pop the top element of the stack, returning both, the top
- element and the updated stack."
- (values (car stack) (cdr stack)))
-
-
- (define empty-stack? null?)
- (define (transfer src dst)
- "Transfer all element of one stack to the other stack, reversing their order,
- as we can only pop elements, which are on top of a stack and
- only push elements onto elements of a stack."
- (cond [(empty-stack? src) dst]
- [else
- (receive (x xs) (pop src)
-
- (transfer xs (push dst x)))]))
-
-
- (define empty-queue (cons empty-stack empty-stack))
- (define (enqueue queue elem)
- "Enqueue an element x into the given queue."
-
-
-
- (match queue
-
-
-
- [(back-stack . front-stack)
- (cons (push back-stack elem)
- front-stack)]
- [_
- (error "enqueue got something else than a queue:" queue)]))
- (define (dequeue queue)
- "Dequeue the head of the queue."
-
-
- (cond
- [(queue-empty? queue)
- (error "cannot dequeue from empty queue")]
- [else
- (match queue
- [(back-stack . front-stack)
- (cond
-
-
-
- [(empty-stack? front-stack)
- (dequeue
- (cons empty-stack
- (transfer back-stack front-stack)))]
-
-
-
- [else
- (receive (elem updated-front-stack) (pop front-stack)
- (values elem (cons back-stack updated-front-stack)))])]
- [_
- (error "dequeue got something else than a queue:" queue)])]))
- (define (queue-empty? queue)
- "Check whether a queue is empty, by checking whether both
- stacks are empty."
- (and (null? (car queue))
- (null? (cdr queue)))))
|