tweak `slicef` to work with 6.0

pull/3/head
Matthew Butterick 10 years ago
parent b519be7f1d
commit 665ef0b517

@ -141,8 +141,8 @@
(check-equal? (slice-at (range 5) 3) '((0 1 2) (3 4))) (check-equal? (slice-at (range 5) 3) '((0 1 2) (3 4)))
(check-equal? (slice-at (range 5) 3 #t) '((0 1 2))) (check-equal? (slice-at (range 5) 3 #t) '((0 1 2)))
(check-equal? (slicef '(1 2 2 1 1 1 2) odd?) '((1) (2 2) (1 1 1) (2))) (check-equal? (slicef '(0 1 2 0 0 0 3) positive?) '((0) (1 2) (0 0 0) (3)))
(check-equal? (slicef '(1 2 2 1 1 1 2) even?) (slicef '(1 2 2 1 1 1 2) odd?)) (check-equal? (slicef '(0 1 2 0 0 0 3) positive?) (slicef '(0 1 2 0 0 0 3) zero?))
(check-equal? (slicef '(1 (1) (1) 1 1 1 (1)) list?) '((1) ((1) (1)) (1 1 1) ((1)))) (check-equal? (slicef '(1 (1) (1) 1 1 1 (1)) list?) '((1) ((1) (1)) (1 1 1) ((1))))
(check-equal? (slicef '(1 2 3 4 5) list?) '((1 2 3 4 5))) (check-equal? (slicef '(1 2 3 4 5) list?) '((1 2 3 4 5)))

@ -13,11 +13,19 @@
(define/typed+provide (slicef xs pred) (define/typed+provide (slicef xs pred)
(All (A) ((Listof A) (A -> Boolean) -> (Listof (Listof A)))) (All (A) ((Listof A) (A -> Boolean) -> (Listof (Listof A))))
(let loop ([xs xs][acc : (Listof (Listof A)) empty]) (define-values (last-list list-of-lists last-negating)
(if (empty? xs) (for/fold: ([current-list : (Listof A) empty]
(reverse acc) [list-of-lists : (Listof (Listof A)) empty]
(let-values ([(cdr-matches rest) (splitf-at (cdr xs) (if (pred (car xs)) pred (λ([x : A]) (not (pred x)))))]) [negating? : Boolean #f])
(loop rest (cons (cons (car xs) cdr-matches) acc)))))) ([x (in-list xs)])
(define current-pred (if negating? (λ: ([x : A]) (not (pred x))) pred))
(if (current-pred x)
(values (cons x current-list) list-of-lists negating?)
(values (cons x null) (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists) (not negating?)))))
(reverse (cons (reverse last-list) list-of-lists)))
(define/typed+provide slicef-at (define/typed+provide slicef-at
;; with polymorphic function, use cased typing to simulate optional position arguments ;; with polymorphic function, use cased typing to simulate optional position arguments

Loading…
Cancel
Save