4.14 Tables
(require rebellion/collection/table) | package: rebellion |
A table
is a data structure made up of a collection of rows. Tables
contain a list of column names —
> (table (columns #:name #:population #:capital-city) (row "Argentina" 43800000 "Buenos Aires") (row "Greece" 10800000 "Athens") (row "Nigeria" 198600000 "Abuja") (row "Japan" 126400000 "Tokyo"))
(table
(columns #:capital-city #:name #:population)
(row "Buenos Aires" "Argentina" 43800000)
(row "Athens" "Greece" 10800000)
(row "Abuja" "Nigeria" 198600000)
(row "Tokyo" "Japan" 126400000))
> (define countries (table (columns #:name #:population #:capital-city) (row "Argentina" 43800000 "Buenos Aires") (row "Greece" 10800000 "Athens") (row "Nigeria" 198600000 "Abuja") (row "Japan" 126400000 "Tokyo"))) > (table-ref countries 3 '#:name) "Japan"
procedure
(table-rows-ref tab pos) → record?
tab : table? pos : natural?
> (define countries (table (columns #:name #:population #:capital-city) (row "Argentina" 43800000 "Buenos Aires") (row "Greece" 10800000 "Athens") (row "Nigeria" 198600000 "Abuja") (row "Japan" 126400000 "Tokyo"))) > (table-rows-ref countries 2) (record #:capital-city "Abuja" #:name "Nigeria" #:population 198600000)
procedure
(table-columns-ref tab column) → immutable-vector?
tab : table? column : keyword?
> (define countries (table (columns #:name #:population #:capital-city) (row "Argentina" 43800000 "Buenos Aires") (row "Greece" 10800000 "Athens") (row "Nigeria" 198600000 "Abuja") (row "Japan" 126400000 "Tokyo"))) > (table-columns-ref countries '#:capital-city) '#("Buenos Aires" "Athens" "Abuja" "Tokyo")
procedure
(table-size tab) → natural?
tab : table?
(define countries (table (columns #:name #:population #:capital-city) (row "Argentina" 43800000 "Buenos Aires") (row "Greece" 10800000 "Athens") (row "Nigeria" 198600000 "Abuja") (row "Japan" 126400000 "Tokyo")))
> (table-size countries) 4
4.14.1 Table Iteration and Comprehensions
> (for/table ([god (in-list (list "Zeus" "hera" "hades" "Athena" "PosEIdon"))]) (define name (string-titlecase god)) (record #:name name #:correct-case? (equal? name god) #:name-length (string-length god)))
(table
(columns #:correct-case? #:name #:name-length)
(row #t "Zeus" 4)
(row #f "Hera" 4)
(row #f "Hades" 5)
(row #t "Athena" 6)
(row #f "Poseidon" 8))
syntax
(for*/table (for-clause ...) body-or-break ... body)
body : record?
procedure
(in-table tab) → (sequence/c record?)
tab : table?
value
> (reduce into-table (record #:person "Sam" #:age 78 #:favorite-color 'green) (record #:person "Jamie" #:age 30 #:favorite-color 'purple) (record #:person "Ned" #:age 40 #:favorite-color 'red))
(table
(columns #:age #:favorite-color #:person)
(row 78 'green "Sam")
(row 30 'purple "Jamie")
(row 40 'red "Ned"))