Forwards and Recursion
Ordinary declarations still precede their uses. Mutual recursion is the case where two routine bodies cannot both come first, so Nucleus provides a narrow forward declaration.
forward sub odd(value as u8) as booleanThe forward contains the routine's complete and only signature. Its later body uses an abbreviated header:
sub odd
if value = 0
return false
end
return even(value - 1)
endThe body does not repeat parameters, result type or fails. This avoids two signatures that could disagree and keeps a streaming compiler from reparsing or reconciling declarations.
Recursive calls use ordinary activations
After a complete signature is known, a routine may call itself. Mutually recursive routines use a forward only for a call whose definition appears later. Each active call retains its own scalar parameters, aggregate bindings and locals.
The implementation publishes an activation-capacity limit. Arguments are evaluated first; a call that would exceed the limit then causes an activation-capacity trap before the new body begins. Recursion is part of the language despite that finite machine limit.
The companion uses even and odd to test 7. The forward makes odd visible inside even; the later abbreviated body completes it. observed finishes at 1.
forward sub odd(value as u8) as boolean
sub even(value as u8) as boolean
if value = 0
return true
end
return odd(value - 1)
end
sub odd
if value = 0
return false
end
return even(value - 1)
end
var observed as u16 = 0
sub main()
if odd(7)
observed = 1
end
endSummary
- A forward declaration supplies one complete routine signature.
- The later definition uses only
sub nameand its body. - Self-recursion needs no special declaration once the signature is known.
- Mutual recursion uses forwards only across declaration-order gaps.
- Active recursive calls remain subject to the published activation capacity.
See program structure, names and recursion. The checked companion is 12-forwards.nu.