From f1514fffe30c40b772e4a1c5f7f5d37f56cd90cd Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Mon, 23 Mar 2020 22:47:52 +0100 Subject: [PATCH] utils: Add lists-transpose. --- utils-tests.rkt | 3 ++- utils.rkt | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/utils-tests.rkt b/utils-tests.rkt index d4c83df..82fa0d4 100644 --- a/utils-tests.rkt +++ b/utils-tests.rkt @@ -128,7 +128,8 @@ (check-equal? (hash->list/ordered #hash((b . 1) (a . 1))) '((a . 1) (b . 1))) (let-values ([(l1 l2) (multi-split-at '((1 2 3) (a b c)) 2)]) - (check-equal? l1 '((1 2) (a b))) (check-equal? l2 '((3) (c))))) + (check-equal? l1 '((1 2) (a b))) (check-equal? l2 '((3) (c)))) + (check-equal? (lists-transpose '((1 2) (a b))) '((1 a) (2 b)))) (test-case "Functions" (check-true (procedure-fixed-arity? not)) diff --git a/utils.rkt b/utils.rkt index 416ba20..d258153 100644 --- a/utils.rkt +++ b/utils.rkt @@ -36,6 +36,7 @@ [hash->list/ordered (-> hash? (listof (cons/c any/c any/c)))] [multi-split-at (-> (listof (listof any/c)) number? (values (listof (listof any/c)) (listof (listof any/c))))] + [lists-transpose (-> (listof (listof any/c)) (listof (listof any/c)))] [procedure-fixed-arity? (-> procedure? boolean?)] [in-random (case-> (-> (stream/c (and/c real? inexact? (>/c 0) ( (integer-in 1 4294967087) (stream/c exact-nonnegative-integer?)) @@ -346,6 +347,19 @@ (match (foldr split-1 (cons '() '()) lsts) [(cons lefts rights) (values lefts rights)])) +;;; Given a list of lists of the same length, transposes them. +;;; +;;; > (lists-transpose '((1 2) (a b))) +;;; '((1 a) (2 b)) +;;; +;;; This function is essentially in-parallel, wrapped in a couple +;;; conversions. +(define lists-transpose + (compose sequence->list + in-values-sequence + ((curry apply) in-parallel))) + + ;;; ========= ;;; Functions ;;; =========