hash.zy 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (def h (hash %a 21 2 5 "c" 'c'))
  2. // testing hget
  3. (assert (== 21 (hget h %a)))
  4. (assert (== 5 (hget h 2)))
  5. (assert (== 'c' (hget h "c")))
  6. // default value
  7. (assert (== 0 (hget h 22 0)))
  8. // testing set
  9. (hset h 'a' 3)
  10. (assert (== 3 (hget h 'a')))
  11. // testing confict resolution
  12. // b and its symbol number have same hash value
  13. (hset h %b 13)
  14. (assert (== 13 (hget h %b)))
  15. // testing delete
  16. (hdel h %a)
  17. // %a should be gone
  18. (assert (== 0 (hget h %a 0)))
  19. (pretty true)
  20. (assert (== (str h)
  21. ` (hash
  22. 2:5
  23. c:'c'
  24. 'a':3
  25. b:13 )
  26. `))
  27. (hdel h (symnum %b))
  28. // b should still be in there
  29. (assert (== 13 (hget h %b)))
  30. (assert (hash? h))
  31. (assert (empty? (hash)))
  32. (assert (not (empty? h)))
  33. // clojure like field access
  34. (defmap ranch)
  35. (def lazy8 (ranch cowboy:"Jim" cowgirl:"Jane"))
  36. (assert (== (:cowboy lazy8) "Jim"))
  37. // not present should return default
  38. (assert (== (:joker lazy8 "gotaway") "gotaway"))
  39. // nested access with (->)
  40. // notice that we do field: while clojure does :field
  41. //
  42. (defmap bunkhouse)
  43. (hset lazy8 bunk1:(bunkhouse bed1:"Howie" bed2: "Mamie"))
  44. (assert (== (-> lazy8 bunk1: bed2:) "Mamie"))
  45. (defmap closet)
  46. (hset (:bunk1 lazy8) closet1:(closet broom:"Nimbuz2"))
  47. (assert (== (-> lazy8 bunk1: closet1: broom:) "Nimbuz2"))
  48. (assert (== (-> lazy8 bunk1:closet1:broom:) "Nimbuz2"))
  49. // delete and print should be okay
  50. (def h (hash key1:"val1" key2:222))
  51. (hget h key1:)
  52. (hset h key3:(list 5 6 7))
  53. (hget h key3:)
  54. h
  55. (hdel h key2:)
  56. h
  57. // hashes should accept arrays as indexes
  58. (hset h [0 0] %a)
  59. (hset h [0 1] %b)
  60. (hset h [1 0] %c)
  61. (hset h [1 1] %d)
  62. (assert (== {h[0 0]} %a))
  63. {h2=(hash [4 4]:%slicekey)}
  64. (hash [4 4]:%slicekey)
  65. // calling functions defined in hashes should work
  66. {h.b = (fn [] 42)}
  67. (assert (== (h.b) 42))