Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-henz authored Jul 3, 2024
1 parent 9d4ccbd commit 245bdc0
Showing 1 changed file with 96 additions and 0 deletions.
96 changes: 96 additions & 0 deletions xml/chapter3/section3/subsection3.xml
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,102 @@ display(get(list("b")));
(e.g., numerically or alphabetically). (Compare
exercise<SPACE/><REF NAME="ex:set-lookup-binary-tree"/> of chapter<SPACE/><REF NAME="chap:data"></REF>.)
<LABEL NAME="ex:3_26"/>
<SOLUTION>
<SNIPPET>
<NAME>ex_3_26_solution</NAME>
<EXAMPLE>ex_3_26_solution_example</EXAMPLE>
<JAVASCRIPT>
// provided by GitHub user devinryu

function entry(tree) { return head(tree); }
function left_branch(tree) { return head(tail(tree)); }
function right_branch(tree) { return head(tail(tail(tree))); }
function make_tree(entry, left, right) {
return list(entry, left, right);
}

// kv is list(key, value)
function adjoin_set(kv, set) {
return is_null(set)
? make_tree(kv, null, null)
: head(kv) === head(entry(set))
? set
: head(kv) &lt; head(entry(set))
? make_tree(entry(set),
adjoin_set(kv, left_branch(set)),
right_branch(set))
: make_tree(entry(set),
left_branch(set),
adjoin_set(kv, right_branch(set)));
}

function make_table() {
let local_table = null;
function lookup(given_key, tree_of_records) {
if (is_null(tree_of_records)) {
return null;
} else {
const this_entry = entry(tree_of_records);
const this_key = head(this_entry);
return given_key === this_key
? this_entry
: given_key &lt; this_key
? lookup(given_key,
left_branch(tree_of_records))
: lookup(given_key,
right_branch(tree_of_records));
}
}
function insert(k, v) {
let record = lookup(k, local_table);
if(is_null(record)) {
local_table = adjoin_set(list(k, v), local_table);
} else {
// do nothing
}
}
function get(k) {
return head(tail(lookup(k, local_table)));
}
function print() {
return display(local_table);
}
function dispatch(m) {
return m === "lookup"
? get
: m === "insert"
? insert
: m === "print"
? print
: error(m, "error");
}
return dispatch;
}
</JAVASCRIPT>
</SNIPPET>
<SNIPPET HIDE="yes">
<NAME>ex_3_26_solution_example</NAME>
<JAVASCRIPT>
const t = make_table();
const get = t("lookup");
const put = t("insert");
const print = t("print");

// The test results

put(3, "d");
put(1, "a");
put(2, "b");
put(2, "c");
put(4, "e");
put(5, "f");

print();

display(get(2)); // displays: "b"
</JAVASCRIPT>
</SNIPPET>
</SOLUTION>
</EXERCISE>

<EXERCISE>
Expand Down

0 comments on commit 245bdc0

Please sign in to comment.