UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ CS2613 Lab 6

Background

Hash tables

Time
20 minutes
Activity
Individual/Small Groups.

Although we've mainly focussed on lists, racket supports many other data structures. One very useful data structure is the hash table These support fast key based retrieval (and updating) of information.

    #lang racket

    (define ht (hash "apple" 'red "banana" 'yellow))

    (module+ test
      (require rackunit)
      (check-equal? (hash-ref ht "apple") 'red))
    (define ht2 (hash-set ht "coconut" 'brown))

    (module+ test
      (check-equal? (hash-ref ht2 "coconut") 'brown)
      (check-exn exn:fail? (lambda () (hash-ref ht "coconut"))))
    (define (census . lst)
      (define (helper lst acc-hash)
        (cond
          [(empty? lst) (hash->list acc-hash)]
          [else
           (let* ([key (first lst)]
                  [current (hash-ref acc-hash key 0)])
             (helper (rest lst)                         ))]))
      (helper lst (hash)))

    (module+ test
      (check-equal?
       (sort (census 1 2 3 1 2) #:key car <) '((1 . 2) (2 . 2) (3 . 1)))
      (check-equal?
       (sort (census "aardvark" "dingo" "buffalo" "buffalo" "bear") #:key car string<?)
       '(("aardvark" . 1) ("bear" . 1) ("buffalo" . 2) ("dingo" . 1))))

Explorer

Time
15 minutes
Activity
Demo
    #lang racket
    (require explorer)

    (define a-list
      (list 1 (list 'foo "hello")
            (hash 'apple "red" 'sky "blue" 'violets "purple")))
    (explore a-list)

Plotting

Time
15 minutes
Activity
Individual/Small Groups
    #lang racket
    (require "calculus.rkt")
    (require plot)

    (plot (list
        (function sin -2pi 2pi)
        (function (lambda (x) (deriv sin x)))))

Discussion

Time
15 minutes
Activity
Group discussion

JSON

Time
35 minutes
Activity
Individual/Small groups

JSON is a common data interchage format. Most modern languages have some way to parse JSON, but it typically still requires some effort to extract the desired data.

    (require explorer)
    (require json)

    (define (read-json-file filename)
      (with-input-from-file filename
        (lambda ()
          (read-json))))

    (define (visualize)
      (explore (read-json-file "errors.json")))
    (module+ test
      (require rackunit)
      (check-equal? (collect-status "errors.json") '("403" "422" "500")))

If you have extra time

Complete the tail recursive version of collect-status.

    (define (collect-status2 filename)
      (define (helper in-lst acc)
        (cond
          [(empty? in-lst) acc]
          [else (helper (rest in-lst)                )]))
      (helper                                  )

    (module+ test
      (require rackunit)
      (check-equal? (collect-status "errors.json") (collect-status2 "errors.json")))