Gaucheのオブジェクトシステムを試す
30分プログラム、その404。最近、Schemeのオブジェクトシステムに興味津々です。
というわけで、Gaucheのオブジェクトシステムを使ってリストを作ってみる。
使い方
;; リストを作る gosh> (define xs (make <my-list> :head 1 :tail (make <my-list> :head 2))) ;; 表示 gosh> (to-string xs) ("1" "2") ;; 長さ gosh> (my-length xs) 2 ;; map gosh> (to-string (my-map xs (cut + 1 <>))) ("2" "3")
ソースコード
#! /opt/local/bin/gosh ;; -*- mode:scheme; coding:utf-8 -*- ;; ;; list.scm - ;; ;; Copyright(C) 2008 by mzp ;; Author: MIZUNO Hiroki / mzpppp at gmail dot com ;; http://howdyworld.org ;; ;; Timestamp: 2008/10/31 22:32:09 ;; ;; This program is free software; you can redistribute it and/or ;; modify it under MIT Lincence. ;; (define-class <my-list> () ((head :init-keyword :head :accessor head) (tail :init-keyword :tail :accessor tail :init-value '()))) (define-method my-length ((self <my-list>)) (if (eq? (tail self) '()) 0 (+ 1 (my-length (tail self))))) (define-method my-map ((self <my-list>) f) (if (eq? (tail self) '()) (make <my-list> :head (f (head self))) (make <my-list> :head (f (head self)) :tail (my-map (tail self) f)))) (define-method to-string ((self <my-list>)) (if (eq? (tail self) '()) (list (x->string (head self))) (cons (x->string (head self)) (to-string (tail self)))))