Corecursion should not be confused with Mutual recursion.
In computer science, corecursion is a type of operation that is dual to recursion. Whereas recursion works analytically, starting on data further from a base case and breaking it down into smaller data and repeating until one reaches a base case, corecursion works synthetically, starting from a base case and building it up, iteratively producing data further removed from a base case. Put simply, corecursive algorithms use the data that they themselves produce, bit by bit, as they become available, and needed, to produce further bits of data. A similar but distinct concept is generative recursion, which may lack a definite "direction" inherent in corecursion and recursion.
Where recursion allows programs to operate on arbitrarily complex data, so long as they can be reduced to simple data (base cases), corecursion allows programs to produce arbitrarily complex and potentially infinite data structures, such as streams, so long as it can be produced from simple data (base cases) in a sequence of finite steps. Where recursion may not terminate, never reaching a base state, corecursion starts from a base state, and thus produces subsequent steps deterministically, though it may proceed indefinitely (and thus not terminate under strict evaluation), or it may consume more than it produces and thus become non-productive. Many functions that are traditionally analyzed as recursive can alternatively, and arguably more naturally, be interpreted as corecursive functions that are terminated at a given stage, for example recurrence relations such as the factorial.
Corecursion can produce both finite and infinite data structures as results, and may employ self-referential data structures. Corecursion is often used in conjunction with lazy evaluation, to produce only a finite subset of a potentially infinite structure (rather than trying to produce an entire infinite structure at once). Corecursion is a particularly important concept in functional programming, where corecursion and codata allow total languages to work with infinite data structures.
Corecursion can be understood by contrast with recursion, which is more familiar. While corecursion is primarily of interest in functional programming, it can be illustrated using imperative programming, which is done below using the generator facility in Python. In these examples local variables are used, and assigned values imperatively (destructively), though these are not necessary in corecursion in pure functional programming. In pure functional programming, rather than assigning to local variables, these computed values form an invariable sequence, and prior values are accessed by self-reference (later values in the sequence reference earlier values in the sequence to be computed). The assignments simply express this in the imperative paradigm and explicitly specify where the computations happen, which serves to clarify the exposition.
A classic example of recursion is computing the factorial, which is defined recursively by 0! := 1 and n! := n × (n - 1)!.
To recursively compute its result on a given input, a recursive function calls (a copy of) itself with a different ("smaller" in some way) input and uses the result of this call to construct its result. The recursive call does the same, unless the base case has been reached. Thus a call stack develops in the process. For example, to compute fac(3), this recursively calls in turn fac(2), fac(1), fac(0) ("winding up" the stack), at which point recursion terminates with fac(0) = 1, and then the stack unwinds in reverse order and the results are calculated on the way back along the call stack to the initial call frame fac(3) that uses the result of fac(2) = 2 to calculate the final result as 3 × 2 = 3 × fac(2) =: fac(3) and finally return fac(3) = 6. In this example a function returns a single value.
This stack unwinding can be explicated, defining the factorial corecursively, as an iterator, where one starts with the case of
1=:0!
n,f=(0,1):(n+1,f x (n+1))
n,f=0,1
n+1,f x (n+1)
+1
-1
n!
There is a connection with denotational semantics, where the denotations of recursive programs is built up corecursively in this way.
In Python, a recursive factorial function can be defined as:
factorial(5)
to compute 5!.A corresponding corecursive generator can be defined as:return
for the only yield
there) to the accumulator argument technique for tail recursion, unwound into an explicit loop. Thus it can be said that the concept of corecursion is an explication of the embodiment of iterative computation processes by recursive definitions, where applicable.
In the same way, the Fibonacci sequence can be represented as:
a,b=(0,1):(b,a+b)
(b,-)
(-,a+b)
Tree traversal via a depth-first approach is a classic example of recursion. Dually, breadth-first traversal can very naturally be implemented via corecursion.
Iteratively, one may traverse a tree by placing its root node in a data structure, then iterating with that data structure while it is non-empty, on each step removing the first node from it and placing the removed node's child nodes back into that data structure. If the data structure is a stack (LIFO), this yields depth-first traversal, and if the data structure is a queue (FIFO), this yields breadth-first traversal:
travnn(t)=auxnn([t])
auxdf([t, ...ts])=val(t); auxdf([ ...children(t), ...ts ])
auxbf([t, ...ts])=val(t); auxbf([ ...ts, ...children(t) ])
Using recursion, a depth-first traversal of a tree is implemented simply as recursively traversing each of the root node's child nodes in turn. Thus the second child subtree is not processed until the first child subtree is finished. The root node's value is handled separately, whether before the first child is traversed (resulting in pre-order traversal), after the first is finished and before the second (in-order), or after the second child node is finished (post-order) assuming the tree is binary, for simplicity of exposition. The call stack (of the recursive traversal function invocations) corresponds to the stack that would be iterated over with the explicit LIFO structure manipulation mentioned above. Symbolically,
dfin(t)=[ ...dfin(left(t)), val(t), ...dfin(right(t)) ]
dfpre(t)=[ val(t), ...dfpre(left(t)), ...dfpre(right(t)) ]
dfpost(t)=[ ...dfpost(left(t)), ...dfpost(right(t)), val(t) ]
"Recursion" has two meanings here. First, the recursive invocations of the tree traversal functions
dfxyz
A breadth-first traversal creating its output in the top-down order, corecursively, can be also implemented by starting at the root node, outputting its value, then breadth-first traversing the subtrees – i.e., passing on the whole list of subtrees to the next step (not a single subtree, as in the recursive approach) – at the next step outputting the values of all of their root nodes, then passing on their child subtrees, etc. In this case the generator function, indeed the output sequence itself, acts as the queue. As in the factorial example above, where the auxiliary information of the index (which step one was at, n) was pushed forward, in addition to the actual output of n!, in this case the auxiliary information of the remaining subtrees is pushed forward, in addition to the actual output. Symbolically,
v,ts=([],[FullTree]):(RootValues(ts),ChildTrees(ts))
auxbf
Notably, given an infinite tree, the corecursive breadth-first traversal will traverse all nodes, just as for a finite tree, while the recursive depth-first traversal will go down one branch and not traverse all nodes, and indeed if traversing post-order, as in this example (or in-order), it will visit no nodes at all, because it never reaches a leaf. This shows the usefulness of corecursion rather than recursion for dealing with infinite data structures. One caveat still remains for trees with the infinite branching factor, which need a more attentive interlacing to explore the space better. See dovetailing.
In Python, this can be implemented as follows.The usual post-order depth-first traversal can be defined as:df(t)
to print the values of the nodes of the tree in post-order depth-first order.
The breadth-first corecursive generator can be defined as:
Initial data types can be defined as being the least fixpoint (up to isomorphism) of some type equation; the isomorphism is then given by an initial algebra. Dually, final (or terminal) data types can be defined as being the greatest fixpoint of a type equation; the isomorphism is then given by a final coalgebra.
If the domain of discourse is the category of sets and total functions, then final data types may contain infinite, non-wellfounded values, whereas initial types do not.[1] [2] On the other hand, if the domain of discourse is the category of complete partial orders and continuous functions, which corresponds roughly to the Haskell programming language, then final types coincide with initial types, and the corresponding final coalgebra and initial algebra form an isomorphism.[3]
Corecursion is then a technique for recursively defining functions whose range (codomain) is a final data type, dual to the way that ordinary recursion recursively defines functions whose domain is an initial data type.[4]
The discussion below provides several examples in Haskell that distinguish corecursion. Roughly speaking, if one were to port these definitions to the category of sets, they would still be corecursive. This informal usage is consistent with existing textbooks about Haskell.[5] The examples used in this article predate the attempts to define corecursion and explain what it is.
The rule for primitive corecursion on codata is the dual to that for primitive recursion on data. Instead of descending on the argument by pattern-matching on its constructors (that were called up before, somewhere, so we receive a ready-made datum and get at its constituent sub-parts, i.e. "fields"), we ascend on the result by filling-in its "destructors" (or "observers", that will be called afterwards, somewhere - so we're actually calling a constructor, creating another bit of the result to be observed later on). Thus corecursion creates (potentially infinite) codata, whereas ordinary recursion analyses (necessarily finite) data. Ordinary recursion might not be applicable to the codata because it might not terminate. Conversely, corecursion is not strictly necessary if the result type is data, because data must be finite.
In "Programming with streams in Coq: a case study: the Sieve of Eratosthenes"[6] we find
(sieve p s) = if div p (hd s) then sieve p (tl s) else conc (hd s) (sieve p (tl s))
hd (primes s) = (hd s) tl (primes s) = primes (sieve (hd s) (tl s))where primes "are obtained by applying the primes operation to the stream (Enu 2)". Following the above notation, the sequence of primes (with a throwaway 0 prefixed to it) and numbers streams being progressively sieved, can be represented as
p,s=(0,[2..]):(hd(s),sieve(hd(s),tl(s)))
sieve
is not guaranteed always to be productive, and could become stuck e.g. if called with [5,10..]
as the initial stream.Here is another example in Haskell. The following definition produces the list of Fibonacci numbers in linear time:
This infinite list depends on lazy evaluation; elements are computed on an as-needed basis, and only finite prefixes are ever explicitly represented in memory. This feature allows algorithms on parts of codata to terminate; such techniques are an important part of Haskell programming.
This can be done in Python as well:[7]
The definition of zipWith
can be inlined, leading to this:
This example employs a self-referential data structure. Ordinary recursion makes use of self-referential functions, but does not accommodate self-referential data. However, this is not essential to the Fibonacci example. It can be rewritten as follows:
This employs only self-referential function to construct the result. If it were used with strict list constructor it would be an example of runaway recursion, but with non-strict list constructor this guarded recursion gradually produces an indefinitely defined list.
Corecursion need not produce an infinite object; a corecursive queue[8] is a particularly good example of this phenomenon. The following definition produces a breadth-first traversal of a binary tree in the top-down manner, in linear time (already incorporating the flattening mentioned above):
bftrav :: Tree a b -> [Tree a b]bftrav tree = tree : ts where ts = gen 1 (tree : ts)
gen 0 p = [] gen len (Leaf _ : p) = gen (len-1) p gen len (Branch _ l r : p) = l : r : gen (len+1) p -- ----read---- ----write-ahead---
-- bfvalues tree = [v | (Branch v _ _) <- bftrav tree]
This definition takes a tree and produces a list of its sub-trees (nodes and leaves). This list serves dual purpose as both the input queue and the result (gen len p
produces its output len
notches ahead of its input back-pointer, p
, along the list). It is finite if and only if the initial tree is finite. The length of the queue must be explicitly tracked in order to ensure termination; this can safely be elided if this definition is applied only to infinite trees.
This Haskell code uses self-referential data structure, but does not essentially depend on lazy evaluation. It can be straightforwardly translated into e.g. Prolog which is not a lazy language. What is essential is the ability to build a list (used as the queue) in the top-down manner. For that, Prolog has tail recursion modulo cons (i.e. open ended lists). Which is also emulatable in Scheme, C, etc. using linked lists with mutable tail sentinel pointer:
bfgen(0, _, []) :- !. % 0 entries in the queue -- stop and close the listbfgen(N, [leaf(_) |P], TS) :- N2 is N-1, bfgen(N2, P, TS).bfgen(N, [branch(_,L,R)|P], [L,R|TS]) :- N2 is N+1, bfgen(N2, P, TS).%% ----read----- --write-ahead--
Another particular example gives a solution to the problem of breadth-first labeling.[9] The function label
visits every node in a binary tree in the breadth first fashion, replacing each label with an integer, each subsequent integer bigger than the last by 1. This solution employs a self-referential data structure, and the binary tree can be finite or infinite.
go :: Tree a b -> [Int] -> (Tree Int Int, [Int]) go (Leaf _) (i:a) = (Leaf i, i+1:a) go (Branch _ l r) (i:a) = (Branch i ln rn, i+1:c) where (ln, b) = go l a (rn, c) = go r bOr in Prolog, for comparison,
label(leaf(_), [I|A], leaf(I), [I+1|A]).label(branch(_,L,R),[I|A], branch(I,Ln,Rn),[I+1|C]) :- label(L, A, Ln, B), label(R, B, Rn, C).
An apomorphism (such as an anamorphism, such as unfold) is a form of corecursion in the same way that a paramorphism (such as a catamorphism, such as fold) is a form of recursion.
The Coq proof assistant supports corecursion and coinduction using the CoFixpoint command.
Corecursion, referred to as circular programming, dates at least to, who credits John Hughes and Philip Wadler; more general forms were developed in . The original motivations included producing more efficient algorithms (allowing a single pass over data in some cases, instead of requiring multiple passes) and implementing classical data structures, such as doubly linked lists and queues, in functional languages.