mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-15 10:02:42 +00:00
72 lines
1.5 KiB
Rust
72 lines
1.5 KiB
Rust
// ./src/std/result/question_mark.md
|
|
|
|
|
|
mod checked {
|
|
#[derive(Debug)]
|
|
enum MathError {
|
|
DivisionByZero,
|
|
NonPositiveLogarithm,
|
|
NegativeSquareRoot,
|
|
}
|
|
|
|
type MathResult = Result<f64, MathError>;
|
|
|
|
fn div(x: f64, y: f64) -> MathResult {
|
|
if y == 0.0 {
|
|
Err(MathError::DivisionByZero)
|
|
} else {
|
|
Ok(x / y)
|
|
}
|
|
}
|
|
|
|
fn sqrt(x: f64) -> MathResult {
|
|
if x < 0.0 {
|
|
Err(MathError::NegativeSquareRoot)
|
|
} else {
|
|
Ok(x.sqrt())
|
|
}
|
|
}
|
|
|
|
fn ln(x: f64) -> MathResult {
|
|
if x <= 0.0 {
|
|
Err(MathError::NonPositiveLogarithm)
|
|
} else {
|
|
Ok(x.ln())
|
|
}
|
|
}
|
|
|
|
// Intermediate function
|
|
fn op_(x: f64, y: f64) -> MathResult {
|
|
// if `div` "fails", then `DivisionByZero` will be `return`ed
|
|
let ratio = div(x, y)?;
|
|
|
|
// if `ln` "fails", then `NonPositiveLogarithm` will be `return`ed
|
|
let ln = ln(ratio)?;
|
|
|
|
sqrt(ln)
|
|
}
|
|
|
|
pub fn op(x: f64, y: f64) {
|
|
match op_(x, y) {
|
|
Err(why) => panic!("{}", match why {
|
|
MathError::NonPositiveLogarithm
|
|
=> "logarithm of non-positive number",
|
|
MathError::DivisionByZero
|
|
=> "division by zero",
|
|
MathError::NegativeSquareRoot
|
|
=> "square root of negative number",
|
|
}),
|
|
Ok(value) => println!("{}", value),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn part0() {
|
|
checked::op(1.0, 10.0);
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|