Skip to content

Instantly share code, notes, and snippets.

Created December 15, 2019 05:21
What would you like to do?
(use gauche.threads)
(define (amb . xs)
(lambda (k)
(if (null? xs)
((thread-specific (current-thread)) #f)
(lambda (x)
(let ((t (make-thread
(lambda ()
(guard (e (else #f))
(lambda (k2)
(thread-specific-set! (current-thread) k2)
(k x))))))))
(thread-start! t)))
(cdr xs))
(k (car xs)))))))
(define (run thunk)
(let ((t
(lambda ()
(guard (e (else #f))
(lambda (k)
(thread-specific-set! (current-thread) k)
((thread-specific (current-thread)) #f))))))))
(thread-start! t)
(thread-join! t)))
;;;; N-Queens
(define (conflict? k qs)
(if (memv k qs)
(let loop ((a (+ k 1)) (b (- k 1)) (qs qs))
(if (null? qs)
(let ((q (car qs)))
(if (or (eqv? a q)
(eqv? b q))
(loop (+ a 1) (- b 1) (cdr qs))))))))
(define (an-element-of items)
(apply amb items))
(define (q m n qs)
(if (= n m)
(let ((k (an-element-of (iota m))))
(if (conflict? k qs)
(q m (+ n 1) (cons k qs))))))
(run (lambda () (format #t "~S\n" (q 8 0 '()))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment