Functional Weave
Code in Python

math.rational@2.0.0

impl/rust/calculate_rational.rs

1,179 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::math_rational_add_rational::add_rational;  ← addRational, another function of this group · built into the same file, even by a slim install
use super::math_rational_divide_rational::divide_rational;  ← divideRational, another function of this group · built into the same file, even by a slim install
use super::math_rational_multiply_rational::multiply_rational;  ← multiplyRational, another function of this group · built into the same file, even by a slim install
use super::math_rational_rational::{rational_from_value, rational_to_value};  ← rational, another function of this group · built into the same file, even by a slim install
use super::math_rational_subtract_rational::subtract_rational;  ← subtractRational, another function of this group · built into the same file, even by a slim install

/// Add, subtract, multiply or divide two fractions exactly.
///
/// The result is always reduced with a positive denominator, so equal values
/// have equal fields.
///
/// # Panics
/// Panics on a zero denominator, division by zero, an unknown operation, or a
/// result outside ±(2^53 - 1).
pub fn calculate_rational(a: &Rational, op: &str, b: &Rational) -> Rational {
    match op {
        "add" => add_rational(a, b),
        "subtract" => subtract_rational(a, b),
        "multiply" => multiply_rational(a, b),
        "divide" => divide_rational(a, b),
        other => panic!("unknown operation \"{}\"", other),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    rational_to_value(&calculate_rational(
        &rational_from_value(&args[0]),
        args[1].as_str(),
        &rational_from_value(&args[2]),
    ))
}