簡體   English   中英

球拍彩虹形狀遞歸

[英]Racket Rainbow Shape Recursion

我正在嘗試在 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)

REPL 中的顯示是在函數返回圖像時完成的。 您的調用(Rainbow a)可以重寫為(begin (circle 20 "solid" ...) ...)cond具有隱式開始,因此在每個遞歸步驟中,添加一個begin ),以"Empty List"結束"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 僅包含彩色圓圈,沒有其他文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM