@@ -1541,6 +1541,50 @@ display(count_pairs(cycle));
1541
1541
would go into an infinite loop. Exercise<SPACE /><REF NAME =" ex:make-cycle" />
1542
1542
constructed such lists.
1543
1543
<LABEL NAME =" ex:find-cycle" />
1544
+ <SOLUTION >
1545
+ <SNIPPET >
1546
+ <EXAMPLE >exercise_3_18_solution_example</EXAMPLE >
1547
+ <JAVASCRIPT >
1548
+ // solution provided by GitHub user clean99
1549
+
1550
+ function contains_cycle(x) {
1551
+ let counted_pairs = null;
1552
+ function is_counted_pair(counted_pairs, x) {
1553
+ return is_null(counted_pairs)
1554
+ ? false
1555
+ : head(counted_pairs) === x
1556
+ ? true
1557
+ : is_counted_pair(tail(counted_pairs), x);
1558
+ }
1559
+ function detect_cycle(x) {
1560
+ if (is_null(x)) {
1561
+ return false;
1562
+ } else if (is_counted_pair(counted_pairs, x)) {
1563
+ return true;
1564
+ } else {
1565
+ counted_pairs = pair(x, counted_pairs);
1566
+ return detect_cycle(tail(x));
1567
+ }
1568
+ }
1569
+ return detect_cycle(x);
1570
+ }
1571
+ </JAVASCRIPT >
1572
+ </SNIPPET >
1573
+ <SNIPPET HIDE =" yes" >
1574
+ <NAME >exercise_3_18_solution_example</NAME >
1575
+ <JAVASCRIPT >
1576
+ const three_list = list("a", "b", "c");
1577
+ const cycle = list("g", "h", "i");
1578
+ set_tail(tail(tail(cycle)), cycle);
1579
+
1580
+ // displays false
1581
+ display(contains_cycle(three_list));
1582
+
1583
+ // displays true
1584
+ display(contains_cycle(cycle));
1585
+ </JAVASCRIPT >
1586
+ </SNIPPET >
1587
+ </SOLUTION >
1544
1588
</EXERCISE >
1545
1589
1546
1590
<EXERCISE >
0 commit comments