[Scheme]Understanding the Yin-Yang Puzzle

1 (let* ((yin
2          ((lambda (cc) (display "@") cc) (call-with-current-continuation (lambda (c) c))))
3        (yang
4          ((lambda (cc) (display "*") cc) (call-with-current-continuation (lambda (c) c)))))
5     (yin yang))

1 (define (make-yang-continuation yin)
2   (lambda (yang)
3     (putc #\*)
4     (yin yang))
5   )

1 (define yin-continuation
2   (lambda (yin)
3     (putc #\@)
4     (let ((yang-continuation (make-yang-continuation yin)))
5       (yang-continuation yang-continuation)))
6   )

1 (yin-continuation yin-continuation)

 1 #lang racket
2
3 (define n 0)
4 (define (putc c)
5   (cond
6     ((< n 100) (set! n (+ n 1)) (display c))
7     ((= n 100) (set! n (+ n 1)) (newline))
8     (else 'ok))
9   )
10
11 (define (make-yang-continuation yin)
12   (lambda (yang)
13     (putc #\*)
14     (yin yang))
15   )
16
17 (define yin-continuation
18   (lambda (yin)
19     (putc #\@)
20     (let ((yang-continuation (make-yang-continuation yin)))
21       (yang-continuation yang-continuation)))
22   )
23
24 (yin-continuation yin-continuation)

(y y) =>

@ ((m y) (m y)) =>
@* (y (m y)) =>

@* @ ((m (m y)) (m (m y))) =>
@* @* ((m y) (m (m y))) =>
@* @** (y (m (m y))) =>

@* @** @ ((m (m (m y))) (m (m (m y)))) =>
@* @** @* ((m (m y)) (m (m (m y)))) =>
@* @** @** ((m y) (m (m (m y)))) =>
@* @** @*** (y (m (m (m y)))) =>

...

ps. 有人看不懂scheme，给个lua的翻译版，应该没有理解障碍了（是移除call/cc后的版本，包含了我部分解题思路）。你觉得这谜题容易懂吗：

 1 local n = 0
2 function putc(c)
3     if n < 100 then
4         n = n + 1
5         io.write(c)
6     elseif n == 100 then
7         n = n + 1
8         os.exit()
9     end
10 end
11
12 function make_yang_continuation(yin)
13     return function(yang)
14         putc('*')
15         yin(yang)
16     end
17 end
18 function yin_continuation(yin)
19     putc('@')
20     local yang_continuation = make_yang_continuation(yin)
21     yang_continuation(yang_continuation)
22 end
23
24 yin_continuation(yin_continuation)

posted @ 2014-05-23 03:10  Scan.  阅读(1271)  评论(0编辑  收藏  举报