简体   繁体   English

球拍彩虹形状递归

[英]Racket Rainbow Shape Recursion

I am trying to make a recursive function in Racket where from a list of colours, the function will print out multiple shapes in that order of colours.我正在尝试在 Racket 中创建一个递归函数,其中从颜色列表中,该函数将按颜色顺序打印出多个形状。 However, the function is not printing anything but "Empty List".但是,该功能除了“空列表”之外不打印任何内容。

#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)

The displaying in REPL is done when a function returns an image. REPL 中的显示是在函数返回图像时完成的。 Your call (Rainbow a) can be rewritten as sequence of (begin (circle 20 "solid" ...) ...) ( cond has implicit begin, so in each recursive step, one begin is added), finished with "Empty List" and begin returns last expression, so "Empty List" is finally returned:您的调用(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"

But you can use print and print that image into REPL:但是您可以使用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)

Note that I used void , so my REPL contains only colored circles and no other text.请注意,我使用了void ,因此我的 REPL 仅包含彩色圆圈,没有其他文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM