I want to define a type for a function that does something and then returns another function of the same type [can be itself]. The obvious idea didn't work ("Illegal cyclic type reference" error):
type Behavior[S] = S => Behavior[S]
Is there something obvious that I am missing here? Also I do not understand how to express an idea of "function returning itself".
Short answer
Long answer (short version)
Terminal F-Coalgebras are pretty cool.
Long answer
Warning: lots of barbed wire & co-bananas, or something...
Ok, so, suppose that you have the concept of a functor
Fthat captures what it means that your behavior "does something". In most libraries is something like this:An
F-coalgebraAis essentially just a function fromAtoF[A]:Now, a terminal
F-coalgebraTis anF-coalgebra which additionally has a property that from every otherF-coalgebraAthere is a mediating morphismA => T(such that everything commutes, blah blah):Can we implement it for arbitrary
F? It turns out we can:For the sake of a concrete example, let's see what that contraption does for the simplest imaginable functor
Option:It turns out that the terminal
F-coalgebra forOptionare the so-called conatural numbers. These are basically the natural numbers, plus countable infinity. These things are nicely suitable for representing lengths of potentially infinite "clicking" processes.Let's try it on a finite behavior:
Now, the above machinery automatically gives us a universal way to translate those counting words into conatural numbers. Let's add a helper method for describing conatural numbers (approximately):
What does it show for the Welsh counting words?
Ok, that's neat. Let's try an infinitely clicking process with just one state that is successor of itself:
How would it now describe the single state
()?Seems to work.
Full code: