vectorを使ったスタック

30分プログラム、その706。Gauchevectorの使い方を調べるついでに、スタックを書いてみました。
gacuhe.arrayよりも使いやすいね。

使い方

(define s (make-stack 10))
(stack-push s 1)
(stack-push s 2)
(stack-push s 3)
s
(stack-top s) ;; => 3
(stack-pop s) ;; => 3
(stack-pop s) ;; => 2
(stack-pop s) ;; => 1
(stack-empty? s)

ソースコード

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; vector.scm -
;;
;; Copyright(C) 2009 by mzp
;; Author: MIZUNO Hiroki / mzpppp at gmail dot com
;; http://howdyworld.org
;;
;; Timestamp: 2009/12/10 20:39:22
;;
;; This program is free software; you can redistribute it and/or
;; modify it under MIT Lincence.
;;

(use gauche.uvector)

(define (make-stack size)
  (cons -1 (make-vector size)))

(define stack-index   car)

(define stack-content cdr)

(define (stack-empty? stack)
  (eq? -1 (stack-index stack)))

(define (stack-top stack)
  (vector-ref (stack-content stack) (stack-index stack)))

(define (stack-pop stack)
  (let1 elem (stack-top stack)
	(set-car! stack (- (stack-index stack) 1))
	elem))

(define (stack-push stack elem)
  (set-car! stack (+ (stack-index stack) 1))
  (vector-set! (stack-content stack) (stack-index stack) elem))

(define s (make-stack 10))
(stack-push s 1)
(stack-push s 2)
(stack-push s 3)
s
(stack-top s) ;; => 3
(stack-pop s) ;; => 3
(stack-pop s) ;; => 2
(stack-pop s) ;; => 1
(stack-empty? s)