exercises2.sml 638 B

12345678910111213141516171819202122232425
  1. type key = string
  2. datatype 'a tree = LEAF | TREE of 'a tree * (key * 'a) * 'a tree
  3. val empty = LEAF
  4. fun insert (LEAF, key, newval) = TREE(LEAF, (key, newval), LEAF)
  5. | insert (TREE(l,(k,v),r), key, newval) =
  6. if key < k
  7. then TREE(insert(l,key,newval),(k,v),r)
  8. else if key > k
  9. then TREE(l,(k,v),insert(r,key,newval))
  10. else TREE(l,(key,newval),r)
  11. (* This is not exhaustive, and will fail if the tree
  12. was not created using `insert` *)
  13. fun lookup (TREE(l,(k,v),r), key) =
  14. if key = k
  15. then v
  16. else if key < k
  17. then lookup (l, key)
  18. else lookup (r, key)
  19. | lookup (LEAF, key) = raise Subscript