Skip to content

fixes #805 #1012

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading