@@ -1592,6 +1592,50 @@ display(count_pairs(cycle));
1592
1592
would go into an infinite loop. Exercise<SPACE /><REF NAME =" ex:make-cycle" />
1593
1593
constructed such lists.
1594
1594
<LABEL NAME =" ex:find-cycle" />
1595
+ <SOLUTION >
1596
+ <SNIPPET >
1597
+ <EXAMPLE >exercise_3_18_solution_example</EXAMPLE >
1598
+ <JAVASCRIPT >
1599
+ // solution provided by GitHub user clean99
1600
+
1601
+ function contains_cycle(x) {
1602
+ let counted_pairs = null;
1603
+ function is_counted_pair(counted_pairs, x) {
1604
+ return is_null(counted_pairs)
1605
+ ? false
1606
+ : head(counted_pairs) === x
1607
+ ? true
1608
+ : is_counted_pair(tail(counted_pairs), x);
1609
+ }
1610
+ function detect_cycle(x) {
1611
+ if (is_null(x)) {
1612
+ return false;
1613
+ } else if (is_counted_pair(counted_pairs, x)) {
1614
+ return true;
1615
+ } else {
1616
+ counted_pairs = pair(x, counted_pairs);
1617
+ return detect_cycle(tail(x));
1618
+ }
1619
+ }
1620
+ return detect_cycle(x);
1621
+ }
1622
+ </JAVASCRIPT >
1623
+ </SNIPPET >
1624
+ <SNIPPET HIDE =" yes" >
1625
+ <NAME >exercise_3_18_solution_example</NAME >
1626
+ <JAVASCRIPT >
1627
+ const three_list = list("a", "b", "c");
1628
+ const cycle = list("g", "h", "i");
1629
+ set_tail(tail(tail(cycle)), cycle);
1630
+
1631
+ // displays false
1632
+ display(contains_cycle(three_list));
1633
+
1634
+ // displays true
1635
+ display(contains_cycle(cycle));
1636
+ </JAVASCRIPT >
1637
+ </SNIPPET >
1638
+ </SOLUTION >
1595
1639
</EXERCISE >
1596
1640
1597
1641
<EXERCISE >
0 commit comments