在Chicken Scheme中模拟typeclass

Mistivia eae9dcdba5 update readme 4 meses atrás
.gitignore eae9dcdba5 update readme 4 meses atrás
LICENSE 98e8c71983 init 4 meses atrás
README.md eae9dcdba5 update readme 4 meses atrás
release-info 98e8c71983 init 4 meses atrás
trait.egg 98e8c71983 init 4 meses atrás
trait.scm 7870c8f6e6 remove tabs 4 meses atrás

README.md

Trait

A trait/typeclass system for Chicken Scheme.

Example

Eq

(import trait)

(define-record point x y)

(define-trait Eq
  (==)
  (/= (lambda (a b) (not (== a b)))))

(define-trait-impl (Eq number?)
  (== =))

(define-trait-impl (Eq symbol?)
  (== eq?))

(define-trait-impl (Eq list?)
  (== equal?))

(define-trait-impl (Eq point?)
  (== (lambda (a b) (and (point? b)
                         (= (point-x a) (point-x b))
                         (= (point-y a) (point-y b))))))

(display (list (== 'a 'a)
               (/= 'a 'a)

               (== 1 1)
               (/= 1 1)

               (== 1 2)
               (/= 1 2)

               (== (list 1 2) (list 1 2))
               (/= (list 1 2) (list 1 2))

               (== (make-point 3 4) (make-point 3 4))
               (/= (make-point 3 4) (make-point 3 4))))

Monad

(import trait)

(define-trait Monad
  (>>=)
  (return))

(define-record nullable is-null value)
(define (make-some value)
  (make-nullable #f value))
(define (make-null)
  (make-nullable #t '()))
(define (nullable-type x)
  (if (nullable-is-null x)
      'null
      'some))

(define-trait-impl (Monad nullable?)
  (>>= (lambda (m f)
         (let ((type (nullable-type m)))
           (cond ((eq? type 'null)
                  (make-null))
                 ((eq? type 'some)
                  (f (nullable-value m)))))))
  (return make-some))

(define (*2 a)
  (make-some (* 2 a)))

(display (nullable-value (>>= (make-some 3) *2)))
(newline)

(display ((with-type nullable? return) 42))
(newline)

(define x (make-some 42))
(display ((with-type-of x return) 81))
(newline)