redblack.sml 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. exception LookupError
  2. type key = string
  3. datatype Color = R | B
  4. datatype 'a Tree = E | T of Color * 'a Tree * (key * 'a) * 'a Tree
  5. val empty = E
  6. fun member key E = false
  7. | member key (T (_, l, (k, _), r)) =
  8. if key < k then member key l
  9. else if key > k then member key r
  10. else true
  11. fun lookup key (T (_, l, (k, v), r)) =
  12. if key < k then lookup key l
  13. else if key > k then lookup key r
  14. else v
  15. | lookup key E = raise LookupError
  16. fun balance (B,T(R,T(R,lll,llb,llr),lb,lr),b,r) = T(R,
  17. T(B,lll,llb,llr),
  18. lb,
  19. T(B,lr,b,r))
  20. | balance (B,T(R,ll,lb,T(R,lrl,lrb,lrr)),b,r) = T(R,
  21. T(B,ll,lb,lrl),
  22. lrb,
  23. T(B,lrr,b,r))
  24. | balance (B,l,b,T(R,T(R,rll,rlb,rlr),rb,rl)) = T(R,
  25. T(B,l,b,rll),
  26. rlb,
  27. T(B,rlr,rb,rl))
  28. | balance (B,l,b,T(R,rl,rb,T(R,rrl,rrb,rrr))) = T(R,
  29. T(B,l,b,rl),
  30. rb,
  31. T(B,rrl,rrb,rrr))
  32. | balance body = T body
  33. fun insert (key,newval) t =
  34. let
  35. fun ins E = T (R, E, (key,newval), E)
  36. | ins (t as T (color, l, (k,v), r)) =
  37. if key < k then balance (color, ins l, (k,v), r)
  38. else if key > k then balance (color, l, (k,v), ins r)
  39. else T(color, l, (key, newval), r)
  40. val T (_, l, b, r) = ins t
  41. in
  42. T (B, l, b, r)
  43. end