Created
December 3, 2009 20:17
-
-
Save drewr/248466 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns user) | |
;; loosely inspired by http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html | |
(defprotocol Cons | |
(car [x]) | |
(cdr [x])) | |
(defprotocol List | |
(head [x]) | |
(tail [x]) | |
(size [x]) | |
(cadr [x]) | |
(cddr [x])) | |
(deftype TCons [_car _cdr] :as this | |
Cons | |
(car [] _car) | |
(cdr [] _cdr) | |
List | |
(head [] (car this)) | |
(tail [] (cdr this)) | |
(size [] (if (cdr this) (inc (size (cdr this))) 1)) | |
(cadr [] (car (cdr this))) | |
(cddr [] (cdr (cdr this)))) | |
(def c1 (TCons 1 nil)) | |
(car c1) ;; 1 | |
(cdr c1) ;; nil | |
(def l1 (TCons 95 (TCons 96 (TCons 97 (TCons 98 nil))))) | |
(head l1) ;; 95 | |
(tail l1) ;; #:TCons{:_car 96, :_cdr #:TCons{:_car 97, :_cdr #:TCons{:_car 98, :_cdr nil}}} | |
(size l1) ;; 4 | |
(cadr l1) ;; 96 | |
(cddr l1) ;; #:TCons{:_car 97, :_cdr #:TCons{:_car 98, :_cdr nil}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment