Thue sequences

Thue sequences, after Axel Thue, are sequences over an alphabet of three {1,2,3} such that no subsequence is immediately repeated. For example, 1213121 is a Thue sequence that cannot be extended 12131211 x, 12131212 x, 12131213 x. However, there are Thue sequences of any length. (There are no solutions longer than 3 for binary sequences, and finding solutions is easier for alphabets larger than three.)

The 'circular program' below [All93] builds a tree of Thue sequences. Note that within function 'build', the tree data-structure 'T' and functions 'toplevel' and 'f' are mutually recursive. The program relies on the fact that a partial soln 'abcde' can be extended with 'f' iff its shadow, 'bcdef', is already in tree at the previous level; this avoids repeating many tests on constraints that have already been treated at a higher level. The subtree for 'abcde' is the subtree of 'bcde' less any 'a' nodes. The tree of all solutions is notionally infinite, but the program prints one branch to a finite depth so only a finite part of the tree is evaluated thanks to lazy evaluation.




There are more λ-calculus examples here.

References

[All89] Lloyd Allison, 'Circular Programs and Self-Referential Structures', Software Practice & Experience, 19(2), pp.99-109, doi:10.1002/spe.4380190202, February 1989.
[All93] Lloyd Allison, 'Applications of Recursively Defined Data Structures', Australian Computer Journal, 25(1), pp.14-20, arxiv:2206.12795, 1993.
And other publications.