Exercise 2.2 (Andersson [And91D]) In the worst case, member performs approximately 2d comparisons, where d is the depth of the tree. Rewrite member to take no more than d + 1 comparisons by keeping track of a candidate element that might be equal to the query element (say, the last element for which < returned false or < returned true) and checking for equality only when you hit the bottom of the tree.)
Answer
To test the example code, run these commands:
erl -noshell -noinit -run ex2_2 test_insert -run init stop
erl -noshell -noinit -run ex2_2 test_member -run init stop
My erlang implementation actually does not have the same performance characteristic as stated in the question. The code in question is this:
1 2 3 4 5 |
|
The if
clause in the above function will cause the Element.lt
to be executed twice per node visit in the worst case scenarios. Hence the 2 * d comparisons.
It does not really apply to my erlang version of code because pattern matching has shortcircuted the comparsion when there is a match. The comparsion is done by the guard
. In a sense I cheated: I did not use a functor to compare the values. This enables me to use the pattern matching.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
|