1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Rational Deduction Algorithm

#![forbid(unsafe_code)]
#![no_std]

extern crate alloc;

use {
    core::{convert::TryFrom, iter::FromIterator},
    exprz::{Expr, Expression},
};

/// Package Version
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Ratio Trait
pub trait Ratio<V>
where
    Self: Into<RatioPair<V>>,
{
    /// Create a new ratio from two base type elements.
    fn new(top: V, bot: V) -> Self;

    /// Get reference to top and bottom of ratio.
    fn cases(&self) -> RatioPairRef<'_, V>;

    /// Get the top element.
    #[inline]
    fn top(self) -> V {
        self.into().top
    }

    /// Get reference to the top element.
    #[inline]
    fn top_ref(&self) -> &V {
        self.cases().top
    }

    /// Get the bottom element.
    #[inline]
    fn bot(self) -> V {
        self.into().bot
    }

    /// Get reference to the bottom element.
    #[inline]
    fn bot_ref(&self) -> &V {
        self.cases().bot
    }

    /// Convert from a `RatioPair`.
    #[inline]
    fn from_pair(pair: RatioPair<V>) -> Self {
        Self::new(pair.top, pair.bot)
    }

    /// Reverse a `Ratio`.
    #[inline]
    fn reverse(self) -> Self {
        let ratio = self.into();
        Self::new(ratio.bot, ratio.top)
    }

    /// Get the default ratio.
    #[inline]
    fn default() -> Self
    where
        V: Default,
    {
        Self::from_pair(Default::default())
    }

    /// Clone a `Ratio`.
    #[inline]
    fn clone(&self) -> Self
    where
        V: Clone,
    {
        Self::new(self.top_ref().clone(), self.bot_ref().clone())
    }

    /// Check if two `Ratio`s are equal.
    #[inline]
    fn eq<RV, R>(&self, other: &R) -> bool
    where
        R: Ratio<RV>,
        V: PartialEq<RV>,
    {
        self.eq_by(other, PartialEq::eq)
    }

    /// Check if two `Ratio`s are equal given the comparison function.
    fn eq_by<RV, R, F>(&self, other: &R, mut eq: F) -> bool
    where
        R: Ratio<RV>,
        F: FnMut(&V, &RV) -> bool,
    {
        eq(self.top_ref(), other.top_ref()) && eq(self.bot_ref(), other.bot_ref())
    }

    /// Check if two `Ratio`s are equal by checking if they cancel symmetrically.
    fn eq_by_symmetric_cancellation<RV, R, F>(&self, other: &R, eq: F) -> bool
    where
        R: Ratio<RV>,
        F: FnMut(&V, &RV) -> bool,
    {
        // FIXME: implement
        let _ = (other, eq);
        todo!()
    }

    /// Compose two ratios using the ratio monoid multiplication algorithm.
    #[inline]
    fn pair_compose<T>(top: Self, bot: Self) -> Self
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        V::Item: PartialEq,
    {
        Self::pair_compose_by(top, bot, PartialEq::eq)
    }

    /// Compose two ratios using the ratio monoid multiplication algorithm.
    fn pair_compose_by<F>(top: Self, bot: Self, eq: F) -> Self
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        F: FnMut(&V::Item, &V::Item) -> bool,
    {
        let top = top.into();
        let bot = bot.into();
        let (lower, upper) = util::multiset_symmetric_difference_by::<_, V, _>(
            top.bot,
            bot.top.into_iter().collect(),
            eq,
        );
        Self::new(
            upper.chain(top.top).collect(),
            lower.into_iter().chain(bot.bot).collect(),
        )
    }

    /// Fold a collection of ratios using [`pair_compose`].
    ///
    /// [`pair_compose`]: trait.Ratio.html#method.pair_compose
    #[inline]
    fn compose<I>(ratios: I) -> Self
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        V::Item: PartialEq,
        I: IntoIterator<Item = Self>,
    {
        Self::compose_by(ratios, PartialEq::eq)
    }

    /// Fold a collection of ratios using [`pair_compose_by`].
    ///
    /// [`pair_compose_by`]: trait.Ratio.html#method.pair_compose_by
    fn compose_by<I, F>(ratios: I, mut eq: F) -> Self
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        I: IntoIterator<Item = Self>,
        F: FnMut(&V::Item, &V::Item) -> bool,
    {
        let mut iter = ratios.into_iter();
        iter.next()
            .map(move |r| iter.fold(r, move |t, b| Self::pair_compose_by(t, b, &mut eq)))
            .unwrap_or_else(|| Self::new(V::from_iter(None), V::from_iter(None)))
    }

    /// Check if there would be any cancellation if you composed the two elements.
    #[inline]
    fn has_cancellation(top: &Self, bot: &Self) -> bool
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        V::Item: PartialEq,
    {
        Self::has_cancellation_by(top, bot, PartialEq::eq)
    }

    /// Check if there would be any cancellation if you composed the two elements.
    fn has_cancellation_by<F>(top: &Self, bot: &Self, eq: F) -> bool
    where
        V: IntoIterator + FromIterator<<V as IntoIterator>::Item>,
        F: FnMut(&V::Item, &V::Item) -> bool,
    {
        let _ = (top, bot, eq);
        /*
        let top = top.cases();
        let bot = bot.cases();
        util::has_intersection_by(top.bot, bot.top.into_iter().collect(), &mut eq)
            || util::has_intersection_by(top.top, bot.bot.into_iter().collect(), &mut eq)
        */
        todo!()
    }
}

/// Ratio Reference Type
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RatioPairRef<'v, V> {
    /// Top of the ratio
    pub top: &'v V,

    /// Bottom of the ratio
    pub bot: &'v V,
}

/// Canonical Ratio Type
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RatioPair<V> {
    /// Top of the ratio
    pub top: V,

    /// Bottom of the ratio
    pub bot: V,
}

impl<V> Ratio<V> for RatioPair<V> {
    #[inline]
    fn new(top: V, bot: V) -> Self {
        Self { top, bot }
    }

    #[inline]
    fn cases(&self) -> RatioPairRef<'_, V> {
        RatioPairRef {
            top: &self.top,
            bot: &self.bot,
        }
    }
}

impl<V> From<(V, V)> for RatioPair<V> {
    #[inline]
    fn from(pair: (V, V)) -> Self {
        Self::new(pair.0, pair.1)
    }
}

impl<V> Ratio<V> for (V, V) {
    #[inline]
    fn new(top: V, bot: V) -> Self {
        (top, bot)
    }

    #[inline]
    fn cases(&self) -> RatioPairRef<'_, V> {
        RatioPairRef {
            top: &self.0,
            bot: &self.1,
        }
    }
}

impl<E> From<RatioPair<E::Group>> for Expr<E>
where
    E: Expression,
    E::Group: IntoIterator<Item = E> + FromIterator<E>,
{
    /// Convert a `RatioPair<E>` into an `Expr<E>` by forgetting the shape of the underlying
    /// expression.
    #[inline]
    fn from(ratio: RatioPair<E::Group>) -> Self {
        Self::Group(
            Some(E::from_group(ratio.top))
                .into_iter()
                .chain(Some(E::from_group(ratio.bot)))
                .collect(),
        )
    }
}

impl<E> TryFrom<Expr<E>> for RatioPair<E::Group>
where
    E: Expression,
    E::Group: IntoIterator<Item = E>,
{
    type Error = expr::RatioPairFromExprError;

    /// Parse an `Expr<E>` into a `RatioPair<E>` if it has the correct shape.
    fn try_from(expr: Expr<E>) -> Result<Self, Self::Error> {
        match expr {
            Expr::Group(group) => {
                let mut iter = group.into_iter();
                if let (Some(top), Some(bot), None) = (iter.next(), iter.next(), iter.next()) {
                    match (top.into(), bot.into()) {
                        (Expr::Group(top), Expr::Group(bot)) => Ok(Self { top, bot }),
                        (_, Expr::Group(_)) => Err(expr::RatioPairFromExprError::MissingTopGroup),
                        (Expr::Group(_), _) => Err(expr::RatioPairFromExprError::MissingBotGroup),
                        _ => Err(expr::RatioPairFromExprError::MissingTopBotGroups),
                    }
                } else {
                    Err(expr::RatioPairFromExprError::BadGroupShape)
                }
            }
            _ => Err(expr::RatioPairFromExprError::NotGroup),
        }
    }
}

/// Expression Ratio Module
pub mod expr {
    use {
        super::Ratio,
        core::{borrow::Borrow, iter::FromIterator},
        exprz::{iter::IteratorGen, Expression},
    };

    /// Conversion from `Expr` to `RatioPair` Error Type
    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    pub enum RatioPairFromExprError {
        /// The expression is not a group.
        NotGroup,

        /// The expression has the wrong group shape.
        BadGroupShape,

        /// The top element of the group is not a group.
        MissingTopGroup,

        /// The bot element of the group is not a group.
        MissingBotGroup,

        /// The top and bot element of the group are not groups.
        MissingTopBotGroups,
    }

    /// Check if an `Expression` has the right shape to be a ratio.
    ///
    /// Use [`try_from`] to convert an `Expr<E>` to a `RatioPair<E>`.
    ///
    /// [`try_from`]: ../struct.RatioPair.html#impl-TryFrom<Expr<E>>
    #[must_use]
    pub fn has_ratio_shape<E>(expr: &E) -> bool
    where
        E: Expression,
    {
        match expr.cases().group() {
            Some(group) => {
                let mut iter = group.iter();
                if let (Some(top), Some(bot), None) = (iter.next(), iter.next(), iter.next()) {
                    top.borrow().is_group() && bot.borrow().is_group()
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    /// Substitute an `Expression` into each `Atom` of `self`.
    #[inline]
    pub fn substitute<E, R, F>(ratio: R, mut f: F) -> R
    where
        E: Expression,
        E::Group: IntoIterator<Item = E> + FromIterator<E>,
        R: Ratio<E::Group>,
        F: FnMut(E::Atom) -> E,
    {
        let ratio = ratio.into();
        Ratio::new(
            ratio
                .top
                .into_iter()
                .map(|e| e.substitute(&mut f))
                .collect(),
            ratio
                .bot
                .into_iter()
                .map(|e| e.substitute(&mut f))
                .collect(),
        )
    }

    /// Evaluate a composition by performing each substitution and then composing ratios.
    #[inline]
    pub fn eval_composition<E, R, F, S, I>(terms: I) -> R
    where
        E: Expression + PartialEq,
        E::Group: IntoIterator<Item = E> + FromIterator<E>,
        R: Ratio<E::Group>,
        F: FnMut(E::Atom) -> E,
        S: AsMut<F>,
        I: IntoIterator<Item = (R, S)>,
    {
        Ratio::compose(
            terms
                .into_iter()
                .map(move |(r, mut s)| substitute(r, s.as_mut())),
        )
    }
}

/// Utilities
pub mod util {
    use {alloc::vec::Vec, bitvec::vec::BitVec, core::iter::FromIterator, exprz::Expression};

    /// Compute the symmetric difference of two multisets.
    #[inline]
    pub fn multiset_symmetric_difference<L, OL>(
        left: L,
        right: Vec<L::Item>,
    ) -> (OL, impl Iterator<Item = L::Item>)
    where
        L: IntoIterator,
        L::Item: PartialEq,
        OL: FromIterator<L::Item>,
    {
        multiset_symmetric_difference_by(left, right, PartialEq::eq)
    }

    /// Compute the symmetric difference of two multisets.
    pub fn multiset_symmetric_difference_by<L, OL, F>(
        left: L,
        right: Vec<L::Item>,
        mut eq: F,
    ) -> (OL, impl Iterator<Item = L::Item>)
    where
        L: IntoIterator,
        OL: FromIterator<L::Item>,
        F: FnMut(&L::Item, &L::Item) -> bool,
    {
        let right_len = right.len();
        let mut matched_indices: BitVec = BitVec::with_capacity(right_len);
        matched_indices.resize(right_len, false);
        (
            left.into_iter()
                .filter(|l| {
                    (&right).iter().enumerate().all(|(i, r)| {
                        if eq(l, r) && !matched_indices[i] {
                            matched_indices.set(i, true);
                            return false;
                        }
                        true
                    })
                })
                .collect(),
            right
                .into_iter()
                .zip(matched_indices)
                .filter_map(move |(r, m)| Some(r).filter(|_| !m)),
        )
    }

    /// See if the two multisets share any elements.
    #[inline]
    pub fn has_intersection<I>(left: I, right: Vec<&I::Item>) -> bool
    where
        I: IntoIterator,
        I::Item: PartialEq,
    {
        has_intersection_by(left, right, PartialEq::eq)
    }

    /// See if the two multisets share any elements.
    pub fn has_intersection_by<I, F>(left: I, right: Vec<&I::Item>, mut eq: F) -> bool
    where
        I: IntoIterator,
        F: FnMut(&I::Item, &I::Item) -> bool,
    {
        left.into_iter()
            .any(move |l| right.iter().all(|r| eq(&l, r)))
    }

    /// Generator for substitution using an iterator.
    #[inline]
    pub fn substitute_iter_on_atoms<'s, E, I>(iter: I, atom: E::Atom) -> E
    where
        E: 's + Expression,
        E::Atom: PartialEq,
        I: IntoIterator<Item = (&'s E::Atom, E)>,
    {
        iter.into_iter()
            .find(|(a, _)| **a == atom)
            .map(move |(_, t)| t)
            .unwrap_or_else(move || E::from_atom(atom))
    }
}