Skip to content

Commit 8b42f06

Browse files
committed
fixes #824
1 parent 7b7e2a5 commit 8b42f06

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

xml/chapter3/section3/subsection1.xml

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,6 +1521,54 @@ display(count_pairs(cycle));
15211521
distinct pairs in any structure. (Hint: Traverse the structure, maintaining
15221522
an auxiliary data structure that is used to keep track of which pairs have
15231523
already been counted.)
1524+
<SOLUTION>
1525+
<SNIPPET>
1526+
<EXAMPLE>exercise_3_17_solution_example</EXAMPLE>
1527+
<JAVASCRIPT>
1528+
function count_pairs(x) {
1529+
let counted_pairs = null;
1530+
function is_counted_pair(current_counted_pairs, x) {
1531+
return is_null(current_counted_pairs)
1532+
? false
1533+
: head(current_counted_pairs) === x
1534+
? true
1535+
: is_counted_pair(tail(current_counted_pairs), x);
1536+
}
1537+
function count(x) {
1538+
if(! is_pair(x) || is_counted_pair(counted_pairs, x)) {
1539+
return 0;
1540+
} else {
1541+
counted_pairs = pair(x, counted_pairs);
1542+
return count(head(x)) +
1543+
count(tail(x)) +
1544+
1;
1545+
}
1546+
}
1547+
return count(x);
1548+
}
1549+
</JAVASCRIPT>
1550+
</SNIPPET>
1551+
<SNIPPET HIDE="yes">
1552+
<NAME>exercise_3_17_solution_example</NAME>
1553+
<JAVASCRIPT>
1554+
const three_list = list("a", "b", "c");
1555+
const one = pair("d", "e");
1556+
const two = pair(one, one);
1557+
const four_list = pair(two, "f");
1558+
const seven_list = pair(two, two);
1559+
const cycle = list("g", "h", "i");
1560+
set_tail(tail(tail(cycle)), cycle);
1561+
1562+
// return 3; return 3; return 3;
1563+
display(count_pairs(three_list));
1564+
display(count_pairs(four_list));
1565+
display(count_pairs(seven_list));
1566+
1567+
// return 3
1568+
display(count_pairs(cycle));
1569+
</JAVASCRIPT>
1570+
</SNIPPET>
1571+
</SOLUTION>
15241572
</EXERCISE>
15251573

15261574
<EXERCISE>

0 commit comments

Comments
 (0)