简体   繁体   English

球拍\\计划中的返回类型

[英]Return types in Racket \ Scheme

I'm new to Scheme and I'm wondering how to tidy up the returned values from a recursive function I wrote as an assignment. 我是Scheme的新手,我想知道如何从我作为赋值编写的递归函数中整理返回的值。 The function simply prints out a BST in order of lowest to highest value. 该功能仅按从最低到最高的顺序打印出BST。 My question is a bit pedantic, but I'm curious. 我的问题有点古怪,但我很好奇。 The output of the function is a list of numbers, but the recursive implementation results in an empty list being returned at the very end. 该函数的输出是一个数字列表,但是递归实现导致在最后返回一个空列表。 ie 8 16 20 '(). 即8 16 20'()。 Is there a simple way to just return the list of numbers and leave out the empty list? 有一种简单的方法可以只返回数字列表,而忽略空列表吗? I can imagine a couple of ways of doing it; 我可以想象有几种方法可以做到。 building a new list or string and returning that at the end, but it would add a fair bit of overhead for such a simple task. 构建一个新的列表或字符串并在最后返回它,但这对于这样一个简单的任务会增加相当大的开销。 Is there any simpler way to achieve this result? 有没有更简单的方法来达到这个结果? Thanks. 谢谢。

Note: The assignment is finished and I should have full marks at this point, so it's not a homework question. 注意:作业已经完成,此时我应该获得满分,所以这不是作业问题。

#lang racket

(define (show lst)

  (cond
    [(null? (cadr lst))
     '()]

    ; recur smaller tree
    [(< (car lst) (caaddr lst))
     (show (cadr lst))
     ])

  ; print cur node
  (writeln (car lst))

  (cond
    [(null? (cadr lst))
     '()]

    ; recur larger tree
    [(show (caddr lst))])

)

(show '(16 (8 (2 () ()) (10 () ())) (20 (18 () ()) (30 () ()))))

You could replace '() by (void) in your code since the REPL will not print this value. 您可以在代码中用(void)替换'() ,因为REPL不会打印此值。 Or just avoid giving return values altogether: 或者只是避免完全给出返回值:

(define (show lst)
  (unless (null? (cadr lst))
    (when (< (car lst) (caaddr lst))
      (show (cadr lst))))
  (writeln (car lst))
  (unless (null? (cadr lst))
    (show (caddr lst))))

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

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