ombre: Make ordering variadic

b4cdfded288a7c4a82e17abec588f0ecfbb27471
Alexis Sellier committed ago 1 parent 3a25ab29
ombre/src/lisp/evaluator.rs +49 -11
1043 1043
            "Divide numbers or calculate reciprocal of a single number",
1044 1044
            intrinsic::div,
1045 1045
        );
1046 1046
        env.intrinsic(
1047 1047
            "mod",
1048 -
            "Calculate the modulo of two numbers",
1048 +
            "Calculate the non-negative modulo of two numbers",
1049 1049
            intrinsic::modulo,
1050 1050
        );
1051 +
        env.intrinsic(
1052 +
            "%",
1053 +
            "Calculate the modulo of two numbers",
1054 +
            intrinsic::remainder,
1055 +
        );
1051 1056
        env.intrinsic(
1052 1057
            "pow",
1053 1058
            "Raise a number to the power of another",
1054 1059
            intrinsic::pow,
1055 1060
        );
1062 1067
        env.intrinsic(
1063 1068
            "or",
1064 1069
            "Logical *or* of two or more boolean values",
1065 1070
            intrinsic::or,
1066 1071
        );
1072 +
        env.intrinsic("=", "Check if all arguments are equal", intrinsic::eq);
1067 1073
        env.intrinsic(
1068 1074
            ">",
1069 1075
            "Check if the first argument is greater than the second",
1070 1076
            intrinsic::gt,
1071 1077
        );
1802 1808
        }
1803 1809
    }
1804 1810
1805 1811
    /// Greater than.
1806 1812
    pub fn gt(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1807 -
        let result = binop(args, |a, b| a > b, |a, b| a > b)?;
1808 -
        Ok(Expr::Bool(result))
1813 +
        ordering(args, |ord| ord.is_gt())
1809 1814
    }
1810 1815
1811 1816
    /// Greater than or equal.
1812 1817
    pub fn gte(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1813 -
        let result = binop(args, |a, b| a >= b, |a, b| a >= b)?;
1814 -
        Ok(Expr::Bool(result))
1818 +
        ordering(args, |ord| ord.is_ge())
1815 1819
    }
1816 1820
1817 1821
    /// Lesser than.
1818 1822
    pub fn lt(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1819 -
        let result = binop(args, |a, b| a < b, |a, b| a < b)?;
1820 -
        Ok(Expr::Bool(result))
1823 +
        ordering(args, |ord| ord.is_lt())
1821 1824
    }
1822 1825
1823 1826
    /// Lesser than or equal.
1824 1827
    pub fn lte(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1825 -
        let result = binop(args, |a, b| a <= b, |a, b| a <= b)?;
1826 -
        Ok(Expr::Bool(result))
1828 +
        ordering(args, |ord| ord.is_le())
1827 1829
    }
1828 1830
1829 1831
    /// Not (!).
1830 1832
    pub fn not(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1831 1833
        <(bool,)>::try_from_args(args).map(|(b,)| Expr::Bool(!b))
1943 1945
                actual: args.len(),
1944 1946
            }),
1945 1947
        }
1946 1948
    }
1947 1949
1948 -
    /// Modulo (%).
1949 -
    pub fn modulo(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1950 +
    /// Remainder (%).
1951 +
    pub fn remainder(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1950 1952
        binop(args, |a, b| Expr::Integer(a % b), |a, b| Expr::Float(a % b))
1951 1953
    }
1952 1954
1955 +
    /// Modulo (mod).
1956 +
    pub fn modulo(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1957 +
        binop(
1958 +
            args,
1959 +
            |a, b| Expr::Integer(a - ((a as f64 / b as f64).floor() as i64) * b),
1960 +
            |a, b| Expr::Float(if b == 0. { a } else { a - (a / b).floor() * b }),
1961 +
        )
1962 +
    }
1963 +
1953 1964
    /// Power (^).
1954 1965
    pub fn pow(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1955 1966
        binop(
1956 1967
            args,
1957 1968
            |a, b| Expr::Integer(a.pow(b as u32)),
2079 2090
            .map(|v| v.try_into().map_err(Error::UnexpectedValue))
2080 2091
            .try_fold(init, |acc, item| item.map(|i| op(acc, i)))
2081 2092
            .map(Into::into)
2082 2093
    }
2083 2094
2095 +
    fn ordering(args: Vec<Expr>, check: impl Fn(std::cmp::Ordering) -> bool) -> Result<Expr> {
2096 +
        let mut args = args.into_iter();
2097 +
        let Some(init) = args.next() else {
2098 +
            return Err(Error::WrongArgumentCount {
2099 +
                expected: 1,
2100 +
                actual: 0,
2101 +
            });
2102 +
        };
2103 +
        Ok(args
2104 +
            .try_fold(init, |prev, curr| {
2105 +
                compare(&prev, &curr).and_then(|ord| if check(ord) { Some(curr) } else { None })
2106 +
            })
2107 +
            .is_some()
2108 +
            .into())
2109 +
    }
2110 +
2084 2111
    fn binop<T>(
2085 2112
        args: Vec<Expr>,
2086 2113
        op: impl Fn(i64, i64) -> T,
2087 2114
        opf: impl Fn(f64, f64) -> T,
2088 2115
    ) -> Result<T> {
2091 2118
            (Expr::Integer(a), Expr::Integer(b)) => Ok(op(a, b)),
2092 2119
            (Expr::Float(a), Expr::Float(b)) => Ok(opf(a, b)),
2093 2120
            _ => Err(Error::ExpectedValue("number")),
2094 2121
        }
2095 2122
    }
2123 +
2124 +
    /// Helper function to compare numeric expressions.
2125 +
    fn compare(a: &Expr, b: &Expr) -> Option<std::cmp::Ordering> {
2126 +
        match (a, b) {
2127 +
            (Expr::Integer(a), Expr::Integer(b)) => Some(a.cmp(b)),
2128 +
            (Expr::Float(a), Expr::Float(b)) => a.partial_cmp(b),
2129 +
            (Expr::Integer(a), Expr::Float(b)) => (*a as f64).partial_cmp(b),
2130 +
            (Expr::Float(a), Expr::Integer(b)) => a.partial_cmp(&(*b as f64)),
2131 +
            _ => None,
2132 +
        }
2133 +
    }
2096 2134
}
2097 2135
2098 2136
#[cfg(test)]
2099 2137
#[allow(clippy::unwrap_used)]
2100 2138
mod tests {