Eduardo Cavazos <[email protected]> writes:

Also, it would be nice to vertically align the decimal
points.

Alex Shinn wrote:

There's currently no easy way to do this, but that's
definitely a useful feature, I'll add it to my TODO list.

Sounds good, thanks!

Here's an update to the 'table' procedure I posted earlier.

Each column width is calculated by "widest-cell + column-gap" where column-gap is a parameter that defaults to 2.

'decimal-places' is a parameter with a default value of 3.

The previous table only allowed two columns. This one allows any number.

Some examples:

> (table (map (lambda (x) (list x (sin x))) (iota 10)))

0  0
1  0.841
2  0.909
3  0.141
4  -0.757
5  -0.959
6  -0.279
7  0.657
8  0.989
9  0.412
> (table (map (lambda (x) (list x (sin x) (cos x))) (iota 10)))

0  0       1
1  0.841   0.54
2  0.909   -0.416
3  0.141   -0.99
4  -0.757  -0.654
5  -0.959  0.284
6  -0.279  0.96
7  0.657   0.754
8  0.989   -0.146
9  0.412   -0.911
> (table (map (lambda (x) (list x (sin x) (cos x) (tan x))) (iota 10)))

0  0       1       0
1  0.841   0.54    1.557
2  0.909   -0.416  -2.185
3  0.141   -0.99   -0.143
4  -0.757  -0.654  1.158
5  -0.959  0.284   -3.381
6  -0.279  0.96    -0.291
7  0.657   0.754   0.871
8  0.989   -0.146  -6.8
9  0.412   -0.911  -0.452
>

So yeah, next step would be decimal place alignment.

Anywho, also consider offering something like this with 'fmt'. I'm sure folks have to cook up stuff like this all the time. It'd be nice to have a basic one with sane defaults that works out of the box.

Ed

(import (xitomatl fmt)
        (dharmalab combinators macros))

(define (round-to n)
  (lambda (x)
    (/ (round (* x (expt 10 n)))
       (expt 10 n))))

(define (transpose lists)
  (if (null? (car lists))
      '()
      (cons (map car lists)
            (transpose (map cdr lists)))))

(define (to-string x)
  (fmt #f x))

(define column-gap     (make-parameter 2))
(define decimal-places (make-parameter 3))

(define (table data)

  (let ((rounder (round-to (decimal-places))))

    (define (widest lst)
      (+ (column-gap)
         (apply max
                (map (compose (string-length to-string rounder)) lst))))

    (let ((column-widths (map widest (transpose data))))

      (fmt #t
           nl
           (join (lambda (row)
                   (apply cat
                          (map (lambda (cell width)
                                 (pad width (rounder cell)))
                               row
                               column-widths)))
                 data
                 nl)
           nl))))

Reply via email to