Skip to content

Instantly share code, notes, and snippets.

@lexi-lambda
Last active August 29, 2015 14:19
Show Gist options
  • Save lexi-lambda/6883bb6d72a3d6ca9988 to your computer and use it in GitHub Desktop.
Save lexi-lambda/6883bb6d72a3d6ca9988 to your computer and use it in GitHub Desktop.
#lang racket/base
(require racket/generic
(prefix-in base: racket/base)
(prefix-in base: racket/list))
;; some simple interfaces — these are unchanged
;; ---------------------------------------------------------------------------------------------------
(define-generics iterator
(iterator-empty? iterator)
(iterator-value iterator)
(iterator-next iterator))
(define-generics iterable
(iterator iterable)
#:defaults
([iterator? (define iterator values)]))
;; new things!
;; ---------------------------------------------------------------------------------------------------
; #:abstract is now possible with this proposal; just a hint to tell users not
; to implement this interface directly
(define-generics #:abstract sequence
(empty? sequence)
(first sequence)
; this indicates that all sequences are also instances of gen:iterable
; it doesn't provide any fallback methods, so it doesn't do much beside
; throw unsupported errors if an implementation doesn't implement these
#:inherit gen:iterable)
; this is a real implementation of a sequence
(define-generics constructed-sequence
[(rest sequence)]
; this inherits sequence, but it also doesn't provide any fallbacks, so
; these need to be provided by implementations of gen:constructed-sequence
#:inherit gen:sequence
; gen:sequence inherits from gen:iterable, so a fallback can be provided for
; gen:iterable implemented in terms of gen:constructed-sequence's methods
#:fallbacks
[(define iterator constructed-iterator)]
; the classic example of a cons sequence is the list
#:defaults
([list? (define empty? base:empty?)
(define first base:first)
(define rest base:rest)]))
; just the implementation of the built-in constructed sequence iterator
(struct constructed-iterator (sequence)
#:methods gen:iterator
[(define iterator-empty (compose empty? constructed-iterator-sequence))
(define iterator-value (compose first constructed-iterator-sequence))
(define iterator-next (compose iterator rest constructed-iterator-sequence))])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment