My final version is a direct translation from Python. Thanks to build-in support for generator, its speed is almost the same as Python. As I quite like using generator and list comprehension in Python, I am not sure I get the right way in Racket.
Moreover, I've only found explicit support for generator in Racket these days, other scheme languages like MIT scheme and chez scheme seem not. So maybe there are some better way or more "schemeic" way to solve this problem and I am very curious about it.
This is my racket code, if needed:
#lang racket (require racket/generator) (define (safe? x y sln) (if (null? sln) #t (let ((px (caar sln)) (py (cadar sln))) (if (or (= y py) (= (- py y) (- px x)) (= (- py y) (- x px))) #f (safe? x y (cdr sln)))))) ; input-> n, output-> a generator that yields ; every possible list of n queens' coordinates (define (nqueen n) (let recur ((x (- n 1))) (generator () (if (= x -1) (yield '()) (for* ([sln (in-producer (recur (- x 1)) (void))] [y (range n)]) (and (safe? x y sln) (yield (cons (list x y) sln))))) (void)))) (for ([e (in-producer (nqueen 8) (void))]) (displayln e))