Skip to content

Instantly share code, notes, and snippets.

@ashton314
Created February 17, 2021 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashton314/dfcfd1ef05f2a51a355808694948c094 to your computer and use it in GitHub Desktop.
Save ashton314/dfcfd1ef05f2a51a355808694948c094 to your computer and use it in GitHub Desktop.
Non-determinism implemented with the call/cc operator in Racket
#lang racket
(define *remaining-choices* '())
(define (choose choices)
(call/cc
(λ (k)
(for ([i (cdr choices)])
(set! *remaining-choices* (cons (cons k i) *remaining-choices*)))
(k (car choices)))))
(define (fail)
(if (empty? *remaining-choices*)
'fail
(let ([next-choice (car *remaining-choices*)])
;; Pop off that choice we just saved
(set! *remaining-choices* (cdr *remaining-choices*))
(match next-choice
[(cons k chosen-one)
(k chosen-one)]))))
(define (find-factor n)
(let ([the-factor (choose (range 2 n))])
(if (= 0 (modulo n the-factor))
the-factor
(fail))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment