Created
January 17, 2015 05:54
-
-
Save angelworm/4f79c062219a9047ca62 to your computer and use it in GitHub Desktop.
4つの数字から10を作る問題のやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(require racket/control) | |
(define (amb args) | |
(shift k | |
(for ([v args]) | |
(k v)))) | |
(define (perm li) | |
(if (null? (cdr li)) | |
(list li) | |
(append-map (lambda (hd) | |
(map (lambda (l) (cons hd l)) (perm (remq hd li)) | |
)) li))) | |
(define (minians a res) | |
(append-map (lambda (exp) | |
(list (list '+ a exp) | |
(list '- a exp) | |
(list '* a exp) | |
(list '/ a exp)) | |
) res)) | |
(define (make-expr li) | |
(foldl minians (list (car li)) (cdr li))) | |
(define (safe-eval cand) | |
(with-handlers ([exn:fail:contract:divide-by-zero? | |
(lambda (exn) +inf.0)]) | |
(eval cand (make-base-namespace)))) | |
(define (print-make10 question) | |
(reset | |
(let* ([q (perm question)] | |
[now (amb q)] | |
[cand (amb (make-expr now))] | |
[ev (safe-eval cand)]) | |
(cond [(eq? ev 10) | |
(printf "~a: ~a\n" cand ev)])))) | |
(print-make10 '(1 1 5 8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment