Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Created August 29, 2018 14:58
Show Gist options
  • Save jorendorff/9b683a689d68ecf96fdf461ac4f56a25 to your computer and use it in GitHub Desktop.
Save jorendorff/9b683a689d68ecf96fdf461ac4f56a25 to your computer and use it in GitHub Desktop.
;; amb.scm - Nondeterminism using call/cc <3
(define (fail)
(error 'require "no solutions"))
(define backtrack fail)
(define (require ok)
(if (not ok)
(backtrack)))
;; Return one of the values in `values` such that all future `(require)` calls
;; are satisfied.
(define (amb . values)
(let ((backtrack-further backtrack))
(call/cc (lambda (ctn)
(define (next values)
(if (null? values)
(backtrack-further)
(begin (set! backtrack
(lambda () (next (cdr values))))
(ctn (car values)))))
(next values)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment