navid/haze / 8ad27175ea7468984a380df035464efe6200afefbd75a9fe1bfd354d46029e85 / samples/baseline/10_named_contracts.hz
10_named_contracts.hz
← samples/baseline · 1161 bytes · raw · download
// 10: named contracts, pure functions in contracts, contract reuse.
pure fn even(n i32) bool => n % 2 == 0
contract Even(n i32) {
pre even(n)
}
fn half(n i32) i32
: Even(n)
: post r => r * 2 == n
=> n / 2
// @summary
// The classic factorial condition with i32 that prevents overflow.
//
// This is basically FactorialCond from the original sketch.
// Note: a static verifier cannot prove the multiplication stays in i32 from
// `r >= 1` alone; as runtime assertions it is checked on every call.
//
// @param n
// The parameter name
contract FactorialCond(n i32) {
pre {
n >= 0
n <= 12
}
post r => r >= 1
}
fn factorial(n i32) i32 : FactorialCond(n) {
if n <= 1
return 1
return n * factorial(n - 1)
}
fn main() {
print(half(10)) // 5
print(factorial(0)) // 1
print(factorial(5)) // 120
print(factorial(12)) // 479001600
// Must be rejected: Reason:
// half(7) pre `even(n)` violated
// factorial(13) pre `n <= 12` violated
// factorial(-1) pre `n >= 0` violated
}