navid/haze / 67bab09d6ce4fc050f342167d2b41517cc673d31ca05891720d1159f7ab04485 / samples/baseline/10_named_contracts.hz

10_named_contracts.hz

← samples/baseline · 1038 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
}