q.scm 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. (module (arguile data q)
  2. #:export (q %mke-q q? q-nil?
  3. enq! deq!
  4. q-hd q-hd! q-tl q-tl! q-len q-len! q-fn q-fn!
  5. q->lst lst->q q->vec vec->q))
  6. (use (arguile base)
  7. (arguile data)
  8. (arguile data vec))
  9. (trans q (len hd tl)
  10. #:init (%mke-q len hd tl)
  11. #:app (case-lambda
  12. (() (deq! self))
  13. ((k) (enq! self k))))
  14. (defp mke-q () (%mke-q 0 '() '()))
  15. (defp q-nil? (q) (0? (q-len q)))
  16. (defp enq! (q obj)
  17. (q-tl! q (cons obj (q-tl q)))
  18. (q-len! q (1+ (q-len q))))
  19. (defp deq! (q)
  20. (if (q-nil? q) (err "Can't dequeue an empty queue!")
  21. (%deq! q)))
  22. (def %deq! (q)
  23. (when (nil? (q-hd q)) (move-tl->hd! q))
  24. (ret val (car (q-hd q))
  25. (q-len! q (1- (q-len q)))
  26. (q-hd! q (cdr (q-hd q)))))
  27. (def move-tl->hd! (q)
  28. (q-hd! q (reverse (q-tl q)))
  29. (q-tl! q '()))
  30. (defp q->lst (q)
  31. (append (q-hd q) (reverse (q-tl q))))
  32. (defp lst->q (lst)
  33. (%mke-q (length lst) lst '()))
  34. (defp q->vec (compose lst->vec q->lst))
  35. (defp vec->q (compose lst->q vec->lst))