我找到了在http://rosettacode.org/wiki/Sierpinski_carpet#Scheme生成Sierpinski地毯的代码 - 但它不会在DrRacket环境或WeScheme中运行。有人可以为这两种环境提供解决方案吗?
答案 0 :(得分:4)
在预先添加
后,看起来这个代码在DrRacket中运行良好#lang racket
表示代码是用Racket编写的。如果这还不够,我可以提供更多细节。
答案 1 :(得分:2)
我已将该程序翻译为在WeScheme下运行。我做了一些改动:而不是使用(显示)和(换行),我使用WeScheme提供的图像基元来制作更好的图像。你可以view the running program and its source code。为方便起见,我还在此处提供了来源:
;; Sierpenski carpet.
;; http://rosettacode.org/wiki/Sierpinski_carpet#Scheme
(define SQUARE (square 10 "solid" "red"))
(define SPACE (square 10 "solid" "white"))
(define (carpet n)
(local [(define (in-carpet? x y)
(cond ((or (zero? x) (zero? y))
#t)
((and (= 1 (remainder x 3)) (= 1 (remainder y 3)))
#f)
(else
(in-carpet? (quotient x 3) (quotient y 3)))))]
(letrec ([outer (lambda (i)
(cond
[(< i (expt 3 n))
(local ([define a-row
(letrec ([inner
(lambda (j)
(cond [(< j (expt 3 n))
(cons (if (in-carpet? i j)
SQUARE
SPACE)
(inner (add1 j)))]
[else
empty]))])
(inner 0))])
(cons (apply beside a-row)
(outer (add1 i))))]
[else
empty]))])
(apply above (outer 0)))))
(carpet 3)
答案 2 :(得分:1)
以下是WeScheme的修改代码。 WeScheme不支持do循环语法,所以我使用srfi-1展开
(define (unfold p f g seed)
(if (p seed) '()
(cons (f seed)
(unfold p f g (g seed)))))
(define (1- n) (- n 1))
(define (carpet n)
(letrec ((in-carpet?
(lambda (x y)
(cond ((or (zero? x) (zero? y))
#t)
((and (= 1 (remainder x 3)) (= 1 (remainder y 3)))
#f)
(else
(in-carpet? (quotient x 3) (quotient y 3)))))))
(let ((result
(unfold negative?
(lambda (i)
(unfold negative?
(lambda (j) (in-carpet? i j))
1-
(1- (expt 3 n))))
1-
(1- (expt 3 n)))))
(for-each (lambda (line)
(begin
(for-each (lambda (char) (display (if char #\# #\space))) line)
(newline)))
result))))