git @ Cat's Eye Technologies define-opaque / master eg / proper-list.scm
master

Tree @master (Download .tar.gz)

proper-list.scm @masterraw · history · blame

; SPDX-FileCopyrightText: In 2023, Chris Pressey, the original author of this work, placed it into the public domain.
; For more information, please refer to <https://unlicense.org/>
; SPDX-License-Identifier: Unlicense

; example usage with Chicken Scheme: csi -q -b proper-list.scm

(load "define-opaque-0.2.scm")

(define-opaque proper-list make-proper-list (selector value) ('nil 0)
  (
    (proper-list? (lambda ()
      #t))
    (nil (lambda ()
      (make-proper-list 'nil 0)))
    (cons (lambda (head-value tail-value)
      ; NB this is not hugely great, as it's a kind of duck-typing.
      (if (tail-value 'proper-list?)
        (make-proper-list 'cons (cons head-value tail-value))
        (error "Tail is not a proper list: " tail-value))))
    (repr (lambda ()
      (cond
        ((equal? selector 'nil)
          '())
        ((equal? selector 'cons)
          (let* ((head (car value)) (tail (cdr value)))
            (cons head (tail 'repr)))))))
  )
)

(define demo (lambda ()
  (let* (
    (list0 (proper-list 'cons 123 (proper-list 'cons 456 (proper-list 'nil))))
  )
    (display (list0 'repr)) (newline)
    ;(display (proper-list 'cons 123 456))  ; this will error!
  )))

(demo)