é決å®æ§è¨ç®
4ã¤ã®æ°åãã10ã«ãªãå¼ãæ¢ãããã°ã©ã (å符ã®åé¡ã¨ãå¼ã°ãã)ãæ¸ãããchooseé¢æ°ã¨failé¢æ°ã¯ã404 Not Foundãypsilonä¸ã§åãããã«å°ãç´ããç©ã
(define *paths* '()) (define *fail* (gensym)) (define (choose choices) (if (null? choices) (fail) (call/cc (lambda (cc) (set! *paths* (cons (lambda () (cc (choose (cdr choices)))) *paths*)) (car choices))))) (define fail #f) (call/cc (lambda (cc) (set! fail (lambda () (if (null? *paths*) (cc *fail*) (let ((p1 (car *paths*))) (set! *paths* (cdr *paths*)) (p1))))))) (define (calc10 a b c d) (define (// a b) (if (zero? b) (fail) (/ a b))) (define (choose-op x) (choose (if (zero? x) `(,+ ,- ,*) `(,+ ,- ,* ,//)))) (set! *paths* '()) (let ((op1 (choose-op b)) (op2 (choose-op c)) (op3 (choose-op d))) (define (infix str) (define op-table (make-eq-hashtable)) (for-each (lambda (lis) (hashtable-set! op-table (car lis) (cadr lis))) `((,+ +) (,- -) (,* *) (,// /))) (format str a (hashtable-ref op-table op1 #f) b (hashtable-ref op-table op2 #f) c (hashtable-ref op-table op3 #f) d)) (cond ((= (op3 (op2 (op1 a b) c) d) 10) (infix "((~a ~a ~a) ~a ~a) ~a ~a")) ((= (op2 (op1 a b) (op3 c d)) 10) (infix "(~a ~a ~a) ~a (~a ~a ~a)")) ((= (op2 (op1 a b) (op3 c d)) 10) (infix "(~a ~a (~a ~a ~a)) ~a ~a")) ((= (op1 a (op3 (op2 b c) d)) 10) (infix "~a ~a ((~a ~a ~a) ~a ~a) ")) ((= (op1 a (op2 b (op3 c d))) 10) (infix "~a ~a (~a ~a (~a ~a ~a))")) (else (fail))))) #| > (calc10 3 3 3 3) "(3 * 3) + (3 / 3)" > (calc10 3 8 8 8) "(3 + 8) - (8 / 8)" > (calc10 4 4 4 4) ; *fail*ã®å¤ã«ãªã \x2E;G38.497c0e53.ed795 |#
ããã¯ãã©ãã¯ãããããåå²ç¹ã§call/ccã§continuationãä¿åããfailãå¼ã°ããæã«ãã®å°ç¹ããå¥ã®å¤ãé¸ã³ç´ããOn Lispã«è¼ã£ã¦ããã³ã¼ãã®ãã°ã (ã¨æã)ãã©ã(eq? (calc10 4 4 4 4) *fail*)
ã*fail*ã®å¤ã«ãªã£ã¦ãã¾ããfailããããã¬ãã«ã¾ã§å¤§åè±åºãã¦ãã¾ãããã ã¨æãã
é¢é£ï¼
- 4つの数字から四則演算で10になるのを見つける - 素人がプログラミングを勉強するブログ(æ¬å¼§ãèæ ®ãã¦ããªããã°ããã)
åèï¼