# Exercise: Building with Variants
#
# Combine variants with other operations.
#
# Your task: Build a safe division function that returns IntResult.
# - If divisor is 0, return Err "division by zero"
# - Otherwise return Ok with the quotient
#
# Remember: i./ returns (quotient success) - check for zero BEFORE dividing.
#
# When done, delete the marker line below.

union IntResult {
    Ok { value: Int }
    Err { error: String }
}

# I AM NOT DONE

: is-ok? ( IntResult -- Bool )
    match
        Ok { >value } -> drop true
        Err { >error } -> drop false
    end
;

: is-err? ( IntResult -- Bool )
    match
        Ok { >value } -> drop false
        Err { >error } -> drop true
    end
;

: safe-divide ( Int Int -- IntResult )
    # If the divisor is zero, return Err "division by zero".
    # Otherwise divide and wrap the quotient in Ok.
    # Hint: inspect the divisor before dividing, and branch on
    # whether it is zero.
    # Your code here
    drop drop 0 Make-Ok
;

: test-safe-divide-ok ( -- )
    10 2 safe-divide is-ok?
    # Do not edit below this line
    test.assert
;

: test-safe-divide-err ( -- )
    10 0 safe-divide is-err?
    # Do not edit below this line
    test.assert
;

: test-safe-divide-value ( -- )
    10 2 safe-divide
    # Do not edit below this line
    match
        Ok { >value } ->
        Err { >error } -> drop 0
    end
    5 test.assert-eq
;
