navid/haze / 221433b37405f424c4ca0e8131b8d4d4c92a29bd547e3562beac70a7b8f81878 / samples/baseline/10_named_contracts.xyz
10_named_contracts.xyz
← samples/baseline · 1042 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
{
return n / 2
}
// 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.
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:
//
// half(7) // pre `even(n)` violated
// factorial(13) // pre `n <= 12` violated
// factorial(-1) // pre `n >= 0` violated
}