On Sun, Aug 5, 2018 at 3:40 PM Matthias Felleisen
<matth...@felleisen.org> wrote:
> I“d write it like this:
> (struct tree (val left right) #:transparent)
> ;; Tree = '() | (tree X Tree Tree)
> (define (printer t0)
>   (local (;; from-t0 : the path from t0 to t
>           (define (printer/acc t from-t0)
>             (cond
>               [(empty? t)
>                (map display (reverse (cons " end" from-t0)))
>                (newline)]
>               [else
>                (define from-t (list* " --> " (tree-val t) from-t0))
>                (printer/acc (tree-left t) from-t)
>                (unless (empty? (tree-right t))
>                  (printer/acc (tree-right t) from-t))])))
>     (printer/acc t0 '())))
> (printer tree1)

I took a while to understand this.  It's brilliant.  (Thanks for
taking the time --- no matter how little that might've been for you.)
FWIW, to understand it, I had to use the substitution method on paper.
  Here's my final version --- using string-join.  Thanks again!

(require racket/local)
(require racket/string)

(define (print-tree-elegant t0)
  (local ((define (format-all-items ls)
            (map (lambda (item) (format "~a" item)) ls))
          (define (printer/acc t path-from-t0-to-t)
              [(empty? t)
                 (reverse (format-all-items path-from-t0-to-t)) " --> "))]
               (define from-t (cons (tree-root t) path-from-t0-to-t))
               (printer/acc (tree-left t) from-t)
               (unless (empty? (tree-right t))
                 (printer/acc (tree-right t) from-t))])))
    (printer/acc t0 '())))

You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to