我正在嘗試在 Racket 中創建一個遞回函式,其中從顏色串列中,該函式將按顏色順序列印出多個形狀。但是,該功能除了“空串列”之外不列印任何內容。
#lang slideshow
(require 2htdp/image)
(define a (list "red" "Orange" "Yellow" "Green" "Blue" "Purple"))
(define (Rainbow lst)
(cond
[(empty? lst) "Empty List"]
[else (circle 20 "solid" (first lst))
(Rainbow (rest lst))]))
(Rainbow a)
uj5u.com熱心網友回復:
REPL 中的顯示是在函式回傳影像時完成的。您的呼叫(Rainbow a)可以重寫為(begin (circle 20 "solid" ...) ...)(cond具有隱式開始,因此在每個遞回步驟中,begin添加一個),完成"Empty List"并begin回傳最后一個運算式的序列,因此"Empty List"最終回傳:
> (begin (circle 20 "solid" "Red")
(begin (circle 20 "solid" "Orange")
(begin (circle 20 "solid" "Yellow")
"Empty List")))
"Empty List"
但是您可以使用print該影像并將其列印到 REPL 中:
#lang slideshow
(require 2htdp/image)
(define a (list "Red" "Orange" "Yellow" "Green" "Blue" "Purple"))
(define (Rainbow lst)
(cond
[(empty? lst) (void)]
[else (print (circle 20 "solid" (first lst)))
(Rainbow (rest lst))]))
(Rainbow a)
請注意,我使用了void,所以我的 REPL 只包含彩色圓圈,沒有其他文本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/356399.html
