如何在列表中执行将所有树的分支作为字符串返回的函数

时间:2016-04-10 08:59:32

标签: tree scheme

enter image description here

例如在这种情况下它应该返回(“casa”“caso”cal“”cola“”coma“”cena“)。

我已经这样做了,尝试使用tail的递归:

(define (palabras-tree tree)
  (palabras-tree-aux '() tree))

(define (palabras-tree-aux l tree)
  (if (leaf? tree)
      (cons (symbol->string (root tree)) l)
      (cons (symbol->string(root tree))
            (fold-right append '() (map (lambda (t)
                                          (string-append (symbol->string (root t)))
                                          (palabras-tree-aux l  t)) (children tree))))))

但它返回了这个:{c a a a a o o o a a m o e a n}

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这是一个可能的实现,没有尾递归(使用DrRacket测试):

(define (all-names tree)
  (let ((first-char (symbol->string (root tree))))
    (if (leaf? tree)
        (list first-char)
        (map (lambda (el) (string-append first-char el))
             (append-map all-names (children tree))))))