Search code examples
lispschemepretty-printchicken-scheme

How to print all the "parts" of a data structure made with defstruct in chicken scheme


Let's say that we have the above code:

(require-extension defstruct)

(defstruct tree height age leaf-color)

(define coconut
  (make-tree height:30
             age: 5
             leaf-color: 'green))

I know i can use (tree-height coconut) to view the height of coconut, but how about all info of coconut in one command? I also tried (tree->alist coconut) that produces: ((height . 30) (age . 5) (leaf-color . 'green)) But i can't use something like: (for-each pp coconut). Is it possible to do it that way or writing my print-tree with the appropriate commands would be the only solution?


Solution

  • So this is not a general solution since it uses the specific tree->alist procedure. Also, the output isn't particularly pretty. As I mentioned in a comment, if you have very specific printing needs, you should look into the format egg.

    (use defstruct)
    
    (defstruct tree height age leaf-color)
    
    (define coconut (make-tree height: 30 age: 5 leaf-color: 'green))
    
    (define (pp-tree t)
      (let loop ((attr (tree->alist t)))
        (cond ((null? attr) 'done)
              (else
                (display (caar attr))(display ": ")
                (display (cdar attr))(newline)
                (loop (cdr attr))))))