Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active December 11, 2022 20:10
Show Gist options
  • Save dhilst/3920b4da168f85e476be4193db541182 to your computer and use it in GitHub Desktop.
Save dhilst/3920b4da168f85e476be4193db541182 to your computer and use it in GitHub Desktop.
#lang racket
(define-syntax data
(syntax-rules ()
[(data _ (ctr args ...) ...)
(begin
(define (ctr args ...) (lambda (ctr ...) (ctr args ...)))
...
)]))
(define-syntax match
(syntax-rules ()
[(match scrutinee ((ctr args ...) body) ...)
(scrutinee (lambda (args ...) body) ...)]))
(pretty-print
(syntax->datum
(expand #'(data option (some x) (none)))))
(data option (some x) (none))
((some 1)
(lambda (x) (format "is some ~a" x))
(lambda () "is none")) ;; outputs "is some 1"
((none)
(lambda (x) (format "is some ~a" x))
(lambda () "is none")) ;; outputs "is none"
(data bool (true) (false))
((true)
(lambda () "is true")
(lambda () "is false")) ;; outputs "is true"
((false)
(lambda () "is true")
(lambda () "is false")) ;; outputs "is false"
(data list (cons x tail) (nil))
((cons 1 (cons 2 (cons 3 (nil))))
(lambda (x l) (format "is cons with ~v" x))
(lambda () "is nil")) ;; outputs "is cons with 1"
((nil)
(lambda (x l) (format "is cons with ~v" x))
(lambda () "is nil")) ;; outputs "is nil"
(pretty-print
(syntax->datum
(expand
#'(match (some 1)
[(some x) (format "is some ~a" x)]
[(none) "is none"]))))
(match (some 1)
[(some x) (format "is some ~a" x)]
[(none) "is none"])
(match (none)
[(some x) (format "is some ~a" x)]
[(none) "is none"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment