Function Preconditions and Postconditions
fun factorial(_ n: Int): Int {
pre {
// Require the parameter `n` to be greater than or equal to zero.
//
n >= 0:
"factorial is only defined for integers greater than or equal to zero"
}
post {
// Ensure the result will be greater than or equal to 1.
//
result >= 1:
"the result must be greater than or equal to 1"
}
if n < 1 {
return 1
}
return n * factorial(n - 1)
}
factorial(5) // is `120`
// Run-time error: The given argument does not satisfy
// the precondition `n >= 0` of the function, the program aborts.
//
factorial(-2)Last updated