Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Created August 23, 2017 21:34
Show Gist options
  • Save jorendorff/f934477aacb6302ed70f084e2ea7ed81 to your computer and use it in GitHub Desktop.
Save jorendorff/f934477aacb6302ed70f084e2ea7ed81 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)))))
(define (reset-amb)
(set! backtrack fail))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment