Skip to content

Commit

Permalink
modules/dsv/table (smooth): Bugfix
Browse files Browse the repository at this point in the history
* modules/dsv/table.scm (smooth): Bugfix: Handle empty lists and lists with
only one element properly.
* tests/table.scm ("smooth: zero elements in a list")
("smooth: one element in a list", "smooth: two elements in a list"): New tests.
  • Loading branch information
artyom-poptsov committed Jul 14, 2024
1 parent 184e32a commit 64f9416
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 19 deletions.
41 changes: 22 additions & 19 deletions modules/dsv/table.scm
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
string*
stylize
sum
smooth
string-slice
table-format-row
table-wrap-row
Expand Down Expand Up @@ -267,25 +268,27 @@ list where each row is represented as a sub-list of strings."
(define (smooth lst)
(define (avg a b)
(/ (+ a b) 2.0))
(let* ((len (length lst))
(indexed-lst (map cons (iota len) lst))
(sorted-lst (sort indexed-lst (lambda (e n) (< (cdr e) (cdr n))))))
(let loop ((idx 0)
(result '()))
(if (= idx (- len 1))
(map cdr
(sort (cons (cons idx
(avg (cdr (list-ref sorted-lst idx))
(cdr (list-ref sorted-lst (- idx 1)))))
result)
(lambda (e n)
(< (car e) (car n)))))
(let ((current (list-ref sorted-lst idx))
(next (list-ref sorted-lst (+ idx 1))))
(loop (+ idx 1)
(cons (cons (car current)
(avg (cdr current) (cdr next)))
result)))))))
(if (< (length lst) 2)
lst
(let* ((len (length lst))
(indexed-lst (map cons (iota len) lst))
(sorted-lst (sort indexed-lst (lambda (e n) (< (cdr e) (cdr n))))))
(let loop ((idx 0)
(result '()))
(if (= idx (- len 1))
(map cdr
(sort (cons (cons idx
(avg (cdr (list-ref sorted-lst idx))
(cdr (list-ref sorted-lst (- idx 1)))))
result)
(lambda (e n)
(< (car e) (car n)))))
(let ((current (list-ref sorted-lst idx))
(next (list-ref sorted-lst (+ idx 1))))
(loop (+ idx 1)
(cons (cons (car current)
(avg (cdr current) (cdr next)))
result))))))))

(define (table-calculate-cell-widths content-width percents)
"Calculate table cell CONTENT-WIDTHS according to percents."
Expand Down
14 changes: 14 additions & 0 deletions tests/table.scm
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,20 @@



(test-equal "smooth: zero elements in a list"
'()
(smooth '()))

(test-equal "smooth: one element in a list"
'(1)
(smooth '(1)))

(test-equal "smooth: two elements in a list"
'(26.0 26.0)
(smooth '(42 10)))



(test-equal "filter-row"
'(("a1" "b1" "c1")
("a3" "b3" "c3"))
Expand Down

0 comments on commit 64f9416

Please sign in to comment.