I have a function that only terminates if it's called with valid arguments, and that is always the case.
Can I prove this conditional termination to obtain executable code, or do I actually have to modify the function such that it also terminates with invalid arguments, then prove that?
You can define the type of only valid arguments
Ooooh, thanks, I'll play around with that.
I did this once https://github.com/IsaFoL/IsaFoL/blob/master/Weidenbach_Book/CDCL/DPLL_W_Implementation.thy#L361, but have forgotten all the details now. I just remember that this is described somewhere in the codegen tutorial
What I did in a similar case is to modify the function definition like this: f x = if valid x then <recursion> else undefined
and then derived a better simp rule afterwards that assumed valid x
and did not have the undefined
Dealing with subtypes can be annoying sometimes
Oh yeah that's even better in my case, thank you!
Yes if valid x
is simple enough and that you do not care about performance…
These two approaches are probably the best ones for most use cases: a simple validity check if performance and decidability of that check is not an issue, and a typedef otherwise.
Another thing you can do is to use the partial_function
command with the (option)
flag, which makes it so that your function logically returns None
in case of nontermination or Some x
in case of termination with a result x
. If your function definition is tail-recursive, you can use partial_function
with the (tailrec)
flag instead and do away with the option type; in that case, the result in nonterminating cases is simply unspecified.
Last updated: Jun 21 2025 at 01:46 UTC