@@ -1521,6 +1521,54 @@ display(count_pairs(cycle));
1521
1521
distinct pairs in any structure. (Hint: Traverse the structure, maintaining
1522
1522
an auxiliary data structure that is used to keep track of which pairs have
1523
1523
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 >
1524
1572
</EXERCISE >
1525
1573
1526
1574
<EXERCISE >
0 commit comments