简体   繁体   English

尝试在计划/球拍中建立列表

[英]Trying to build a list in Scheme/Racket

I'm very new to Scheme and can't grasp why this isn't working for me. 我对Scheme非常陌生,无法理解为什么这对我不起作用。 I'm trying to return an ordered list from a BST structure, but can't seem to get it to cons or append the car to the list. 我正在尝试从BST结构返回有序列表,但似乎无法使其利弊或将汽车附加到列表中。 I'm obviously doing something wrong. 我显然做错了。 Any suggestions? 有什么建议么? Thanks. 谢谢。

(define (sortList lst)
  (printList '(16 (8 (2 () ()) (10 () ())) (20 (18 () ()) (30 () ()))) (list) )
)

(define (printList lst sorted)

  ; recur smaller
  (unless (null? (cadr lst))
    (cons (printList (cadr lst) sorted) sorted))

  ; debugging...
  (writeln (car lst))

  ; build sorted list
  (cons (car lst) sorted )

  ; recur larger
  (unless (null? (caddr lst))
    (cons (printList (caddr lst) sorted) sorted))

  ; return sorted lst
  sorted
)

I whipped up a quick solution: 我提出了一个快速解决方案:

(define (tree->list tree)
  (let recur ((x tree)
              (acc '()))
    (if (null? x)
        acc
        (recur (cadr x)
               (cons (car x)
                     (recur (caddr x) acc))))))

Example: 例:

> (tree->list '(16 (8 (2 () ()) (10 () ())) (20 (18 () ()) (30 () ()))))
(2 8 10 16 18 20 30)

The way this works is that I have an accumulator ( acc ) which starts as an empty list. 这种工作方式是,我有一个累加器( acc ),它从一个空列表开始。 Then the recursive function ( recur ) checks if the current element is empty: if so, then don't change the accumulator; 然后,递归函数( recur )检查当前元素是否为空:如果是,则不要更改累加器; otherwise, recurse into the right-hand branch, then add the current element to the result, then recurse into the left-hand branch with that. 否则,递归到右手分支,然后将当前元素添加到结果中,然后与此递归到左手分支。

cons builds lists right-to-left, hence the recursion into the right-hand branch before the left-hand branch. cons从右到左构建列表,因此递归到左分支之前的右分支。 (Otherwise, the list will come out reversed.) (否则,列表将相反。)

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

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