From 64f94165631316b5e570904779d49c0a16be782c Mon Sep 17 00:00:00 2001 From: "Artyom V. Poptsov" Date: Sun, 14 Jul 2024 16:09:24 +0300 Subject: [PATCH] modules/dsv/table (smooth): Bugfix * 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. --- modules/dsv/table.scm | 41 ++++++++++++++++++++++------------------- tests/table.scm | 14 ++++++++++++++ 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/modules/dsv/table.scm b/modules/dsv/table.scm index b4d58fb..62aff19 100644 --- a/modules/dsv/table.scm +++ b/modules/dsv/table.scm @@ -32,6 +32,7 @@ string* stylize sum + smooth string-slice table-format-row table-wrap-row @@ -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." diff --git a/tests/table.scm b/tests/table.scm index 8c6d19b..851aafe 100644 --- a/tests/table.scm +++ b/tests/table.scm @@ -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"))