From 8b42f061928971f721240f5843a2b67f6d0fd168 Mon Sep 17 00:00:00 2001 From: henz Date: Mon, 1 Jul 2024 10:51:08 +0800 Subject: [PATCH 1/2] fixes #824 --- xml/chapter3/section3/subsection1.xml | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/xml/chapter3/section3/subsection1.xml b/xml/chapter3/section3/subsection1.xml index 4a219a588..7d5fa20f9 100644 --- a/xml/chapter3/section3/subsection1.xml +++ b/xml/chapter3/section3/subsection1.xml @@ -1521,6 +1521,54 @@ display(count_pairs(cycle)); distinct pairs in any structure. (Hint: Traverse the structure, maintaining an auxiliary data structure that is used to keep track of which pairs have already been counted.) + + + exercise_3_17_solution_example + +function count_pairs(x) { + let counted_pairs = null; + function is_counted_pair(current_counted_pairs, x) { + return is_null(current_counted_pairs) + ? false + : head(current_counted_pairs) === x + ? true + : is_counted_pair(tail(current_counted_pairs), x); + } + function count(x) { + if(! is_pair(x) || is_counted_pair(counted_pairs, x)) { + return 0; + } else { + counted_pairs = pair(x, counted_pairs); + return count(head(x)) + + count(tail(x)) + + 1; + } + } + return count(x); +} + + + + exercise_3_17_solution_example + +const three_list = list("a", "b", "c"); +const one = pair("d", "e"); +const two = pair(one, one); +const four_list = pair(two, "f"); +const seven_list = pair(two, two); +const cycle = list("g", "h", "i"); +set_tail(tail(tail(cycle)), cycle); + +// return 3; return 3; return 3; +display(count_pairs(three_list)); +display(count_pairs(four_list)); +display(count_pairs(seven_list)); + +// return 3 +display(count_pairs(cycle)); + + + From e06860e6f66935b794677a8d109011baa9b72a55 Mon Sep 17 00:00:00 2001 From: henz Date: Mon, 1 Jul 2024 10:52:48 +0800 Subject: [PATCH 2/2] fixes #824 --- xml/chapter3/section3/subsection1.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/xml/chapter3/section3/subsection1.xml b/xml/chapter3/section3/subsection1.xml index 7d5fa20f9..0f965dfb0 100644 --- a/xml/chapter3/section3/subsection1.xml +++ b/xml/chapter3/section3/subsection1.xml @@ -1525,6 +1525,8 @@ display(count_pairs(cycle)); exercise_3_17_solution_example +// solution provided by GitHub user clean99 + function count_pairs(x) { let counted_pairs = null; function is_counted_pair(current_counted_pairs, x) {