Skip to content

Instantly share code, notes, and snippets.

@pnwamk
Created December 6, 2016 17:28
Show Gist options
  • Select an option

  • Save pnwamk/7546a47621647da881c20a3ea183bfdc to your computer and use it in GitHub Desktop.

Select an option

Save pnwamk/7546a47621647da881c20a3ea183bfdc to your computer and use it in GitHub Desktop.
#lang racket
(require racket/unsafe/ops)
(struct Cons (a d) #:transparent
#:methods gen:equal+hash
[(define (equal-proc c1 c2 =?)
(and (=? (unsafe-struct-ref c1 0)
(unsafe-struct-ref c2 0))
(=? (unsafe-struct-ref c1 1)
(unsafe-struct-ref c2 1))))
(define (hash-proc c rec)
(unsafe-fxior (rec (unsafe-struct-ref c 0))
(rec (unsafe-struct-ref c 1))))
(define (hash2-proc c rec)
(unsafe-fxior (rec (unsafe-struct-ref c 0))
(rec (unsafe-struct-ref c 1))))])
(define c1 (Cons 'a 'b))
(define c2 (Cons 'a 'd))
(define c3 (Cons 'b 'b))
(struct Pair (a d) #:transparent)
(define p1 (Pair 'a 'b))
(define p2 (Pair 'a 'd))
(define p3 (Pair 'b 'b))
(define (equal-test str v1 v2 v3)
(displayln str)
(time (for ([_ (in-range 1000000)])
(define ans1 (equal? v1 v1))
(define ans2 (equal? v1 v2))
(define ans3 (equal? v1 v3))
(void))))
(equal-test "Cons equal?" c1 c2 c3)
(equal-test "Pair equal?" p1 p2 p3)
#|
Cons equal?
cpu time: 473 real time: 477 gc time: 27
Pair equal?
cpu time: 216 real time: 218 gc time: 0
|#
(define (hash-test str v1)
(displayln str)
(time (for ([_ (in-range 1000000)])
(define ans1 (equal-hash-code v1))
(define ans2 (equal-secondary-hash-code v1))
(void))))
(hash-test "Cons hash" c1)
(hash-test "Pair hash" p1)
#|
Cons hash
cpu time: 330 real time: 333 gc time: 4
Pair hash
cpu time: 153 real time: 155 gc time: 0
|#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment