Created
May 24, 2012 19:52
-
-
Save rhcarvalho/2783825 to your computer and use it in GitHub Desktop.
Summarizing a sequence with Racket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
;; Summarizes a sequence of things | |
(define (summarize seq) | |
(foldl -append-element '() seq)) | |
(define (-append-element el lst) | |
(match lst | |
['() | |
(list (hash 'what el 'start 0 'end 1))] | |
[(list hs ... (hash-table ('what (? (curry equal? el))) ('start s) ('end e))) | |
(append hs (list (hash 'what el 'start s 'end (add1 e))))] | |
[(list _ ... (hash-table ('what _) ('start _) ('end e))) | |
(append lst (list (hash 'what el 'start e 'end (add1 e))))] | |
[else 'ops])) | |
;------------------------------------------------------------------------ | |
; Tests | |
(require rackunit) | |
(check-equal? (-append-element 42 '()) | |
'(#hash((what . 42) (start . 0) (end . 1)))) | |
(check-equal? (-append-element 42 '(#hash((what . 42) (start . 0) (end . 1)))) | |
'(#hash((what . 42) (start . 0) (end . 2)))) | |
(check-equal? (-append-element 22 '(#hash((what . 42) (start . 0) (end . 1)))) | |
'(#hash((what . 42) (start . 0) (end . 1)) #hash((what . 22) (start . 1) (end . 2)))) | |
(check-equal? (summarize '()) '()) | |
(check-equal? (summarize '(αβ)) '(#hash((what . αβ) (start . 0) (end . 1)))) | |
(check-equal? (summarize '(αβ 你好)) '(#hash((what . αβ) (start . 0) (end . 1)) | |
#hash((what . 你好) (start . 1) (end . 2)))) | |
(check-equal? (summarize '(αβ αβ 你好)) '(#hash((what . αβ) (start . 0) (end . 2)) | |
#hash((what . 你好) (start . 2) (end . 3)))) | |
(check-equal? (summarize '(αβ αβ 你好 你好 你好 שלום-עולם)) '(#hash((what . αβ) (start . 0) (end . 2)) | |
#hash((what . 你好) (start . 2) (end . 5)) | |
#hash((what . שלום-עולם) (start . 5) (end . 6)))) | |
(define ☠ '(1 2 3 a b c 1 1 2 1 1 1 1 2 2 2 c c c c c 1)) | |
(check-equal? (summarize ☠) '(#hash((end . 1) (start . 0) (what . 1)) | |
#hash((end . 2) (start . 1) (what . 2)) | |
#hash((end . 3) (start . 2) (what . 3)) | |
#hash((end . 4) (start . 3) (what . a)) | |
#hash((end . 5) (start . 4) (what . b)) | |
#hash((end . 6) (start . 5) (what . c)) | |
#hash((end . 8) (start . 6) (what . 1)) | |
#hash((end . 9) (start . 8) (what . 2)) | |
#hash((end . 13) (start . 9) (what . 1)) | |
#hash((end . 16) (start . 13) (what . 2)) | |
#hash((end . 21) (start . 16) (what . c)) | |
#hash((end . 22) (start . 21) (what . 1)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment