【问题标题】:Specialising traits with implementations of ops使用操作实现专门化特征
【发布时间】:2022-01-27 14:56:21
【问题描述】:

我计划今年春天学习 Rust,读完这本书后,我选择了一个算法问题来实现来测试自己。马上,我遇到了一个问题,表明我根本不了解特征。

我的项目将是使用各种技术计算范围最小查询,并且因为我对同一事物有多个实现,所以我认为特征是要走的路。我需要的是以下操作:获取基础序列的长度,获取给定索引处的值,并找到具有最小值的第一个索引。这很简单,但后来我想如果我可以使用下标语法访问元素会很好,所以我也想要std::ops::Index<> trait。

这就是我的特质:

/// The type we use for indexing into our arrays.
type Idx = usize;
/// The type our arrays hold. 32-bit are enough for genomic data.
type Val = u32;

/// Range Minimum Query interface.
pub trait RMQArray: std::ops::Index<Idx, Output = Val> {
    /// Get the length of the underlying array.
    fn len(&self) -> Idx;
    /// Get the value at a specific index.
    fn val(&self, index: Idx) -> &Val;
    /// Get the index of the first minimal value in the range [i,j).
    fn rmq(&self, i: Idx, j: Idx) -> Idx;

    // Interface for Index<Idx, Output = Val>
    fn index(&self, index: Idx) -> &Val {
        self.val(index)
    }
}

前三个方法是具体实现应该提供的,index方法实现Index&lt;Idx&gt;。

但是,只有在每个具体实现都重新实现 index 方法以提供 Index&lt;&gt; 实现时,我才能让它工作。

/// Implements RMQ by running through the [i,j) interval
/// and finding the index with the smallest value.
/// O(1) preprocessing and O(n) access.
pub struct BruteForceRMQ {
    values: Vec<u32>,
}

impl BruteForceRMQ {
    pub fn new(values: Vec<u32>) -> BruteForceRMQ {
        BruteForceRMQ { values }
    }
}

// Implementing the Index<> interface. This is redundant
// if I need it for each implementation of RMQArray.
impl std::ops::Index<Idx> for BruteForceRMQ {
    type Output = Val;
    fn index(&self, index: Idx) -> &Val {
        self.val(index)
    }
}

impl RMQArray for BruteForceRMQ {
    fn len(&self) -> Idx { ... }
    fn val(&self, index: Idx) -> &Val { ... }
    fn rmq(&self, i: Idx, j: Idx) -> Idx {... }
}

我所有的实现,无一例外,都将实现完全相同的Index&lt;&gt; 接口。它们都将具有Output = Val 并且index() 方法将始终委托给val(),因此为它们中的每一个实现Index&lt;&gt; trait 是多余的。

我曾认为我可以将Index&lt;&gt; 专精于RMQArray,但我做不到。比我聪明的人可能可以,但我还没有弄清楚。

我也尝试过使用 mixin 之类的东西,这样我就可以通过这种方式将功能融入到具体的实现中,但是我从其他语言中学到的技巧在 Rust 中没有一个对我有用。无论如何,这可能不是正确的方式,但我不知道 Rust 方式是什么。

什么是实现专门化其他特征的新特征的正确方法,所以我只需要从具体实现中实现我自己的特征所需的少数方法,然后它会调整这些方法,为我提供接口遗传特征?

更新

所以,我可以通过宏到达那里:

macro_rules! adapt_index {
    ($t:ident) => {
        impl std::ops::Index<Idx> for $t {
            type Output = Val;
            fn index(&self, index: Idx) -> &Val {
                self.val(index)
            }
        }
    };
}

但是当它是完全相同的代码并且所有人都必须实现它时,我必须将该宏应用于RMQArray 的所有实现,这仍然让人感到烦人。这是一个比为每个实例编写样板代码更好的解决方案,但它仍然是一个糟糕的解决方案。

然后我想,如果我不能在RMQArray 中实现Index&lt;&gt; trait,也许我可以为RMQArray 的所有实例添加通用代码,所以我尝试了这个:

impl<T> std::ops::Index<Idx> for T
where
    T: RMQArray,
{
    type Output = Val;
    fn index(&self, index: Idx) -> &Self::Output {
        self.val(index)
    }
}

不行。这违反了孤儿规则;由于某种原因,我不允许在这里扩展 Index&lt;&gt;,这与 T 可能来自另一个包有关(我认为是,我不能说我已经以任何有意义的方式了解了 Rust 的类型系统)。

在我看来,它描述了如何为实现 RMQArray 的所有类型实现 Index 似乎是合理的,我猜确实如此,但这也有道理,这可能会混淆其他包的相同实现。

我尝试解决这个问题,但一直回到需要动态调度和不适用于泛型的解决方案,所以这种方法也没有运气。

我可以让它为我自己的特征工作,但如果它是 Index&lt;&gt; 我需要下标语法糖,那就没用了。我不禁想到,对于本质上是微不足道的委托/适配器模式,必须有一个标准的 Rust 解决方案,但我可能以一种完全错误的方式思考这个问题,我应该从根本上重新设计它。

【问题讨论】:

  • 我认为您可以做的是为您的 trait 实现 Index,使用它,您必须对 trait 对象 (Box&lt;dyn RMQArray&gt;) 进行操作。 Playground 示例play.rust-lang.org/… 我不是 100% 确定这是否是您正在寻找的东西。
  • 这似乎适用于动态调度。但是,不适用于泛型,我仍然必须复制所有具体类型的实现。我可以用一个宏来解决它,但这仍然是一个非常糟糕的解决方案。但也许 Rust 不能以这种方式适应特征,我应该使用其他一些方法......不知道......
  • 要走的路正好相反:而不是要求val() 并提供Index impl(由于连贯性你不能这样做),你应该要求Index impl 和(如果需要)基于此提供val()。
  • @ChayimFriedman 我想走另一条路的原因是在实现索引时有很多样板代码,而val 是一个单一的方法。我真的不需要val,这只是试图避免Index&lt;&gt;;如果我有Index&lt;&gt;,我根本不会打扰val。
  • 那么你可以使用宏,但除此之外,我认为你没有什么可以做的。见How do I implement a trait I don't own for a type I don't own?

标签: inheritance rust traits


【解决方案1】:

也许你根本不需要RMQArray。

像this这样直接使用宏会更好吗?

【讨论】:

  • 我不确定我是否需要这个特性——我不能说我完全理解泛型类型的 Rust 方法——但我只有一堆我想要的算法检查范围最小查询的不同实现的性能。我的印象是我需要一个 trait 来指定泛型参数实现的内容。不过,我无法在宏中实现 RMQArray 方法;对于不同的实现,它们是不同的。我只是希望它们都以自己特定的方式支持索引。
【解决方案2】:

根据一些建议,我想出了一个解决方案。我不确定这是否是一个好的解决方案,但我得到了我想要的没有宏。相反,我必须包装我的类型,所以我有与宏相同数量的样板,但至少它是不同的......

我有一个具体类型必须实现的接口,就像以前一样:

type Idx = usize;
type Val = u32;

/// To make a RMQArray, you should implement this and then wrap the type
/// in RMQArray_<>.
pub trait RMQArrayImpl {
    fn new(values: Vec<Val>) -> Self;
    fn len(&self) -> Idx;
    fn val(&self, index: Idx) -> &Val;
    fn rmq(&self, i: Idx, j: Idx) -> Idx;
}

它没有 Index&lt;&gt; trait 作为先决条件,因为我不想在具体类型中实现它,但我添加了另一个需要 RMQArrayImpl 和 std::ops::Index&lt;Idx&gt; 的类型:

/// Range Minimum Query interface.
/// We are just telling the type system that RMQArray implements RMQArrayImpl
/// and Index<Idx>.
pub trait RMQArray: RMQArrayImpl + std::ops::Index<Idx, Output = Val> {}

这和以前没什么不同,但现在我添加了一个包装器类型。它的工作是给我一个可以扩展的本地类型,而不是尝试扩展 Rust 不允许的 Index&lt;&gt; 接口。

/// Wrapper type to extend RMQArrayImpl.
pub struct RMQArray_<Impl: RMQArrayImpl>(Impl);

我的想法是我所有的具体实现都是RMQArrayImpl,然后我将它们包装成RMQArray_&lt;&gt;,而后者我可以在通用实现中扩展。

我需要包装器类型来实现RMQArrayImpl,我找不到比包装整个接口更好的方法。如果有,请告诉我。

/// A delegate that pulls the interface from T into RMQArray_<T>.
impl<T> RMQArrayImpl for RMQArray_<T>
where
    T: RMQArrayImpl,
{
    fn new(values: Vec<Val>) -> Self     { RMQArray_::<T>(T::new(values)) }
    fn len(&self) -> Idx                 { self.0.len() }
    fn val(&self, i: Idx) -> &Val        { self.0.val(i) }
    fn rmq(&self, i: Idx, j: Idx) -> Idx { self.0.rmq(i, j) }
}

我也想让包装器类型实现RMQArray,不过这里没什么可做的。它已经实现了RMQArrayImpl,它会在一秒钟内实现Index&lt;Idx&gt;,所以它只是:

/// Make sure that an RMQArray_<T> implements RMQArray.
/// There is nothing to implement, we get it all from RMQArrayImpl,
/// but we still need to tell the type system.
impl<T> RMQArray for RMQArray_<T> where T: RMQArrayImpl {}

然后是实现Index&lt;Idx&gt; 接口的通用代码。这是我以前无法做到的,我尝试为实现RMQArray的所有类型T实现它,但如果T实现RMQArrayImpl,我可以为所有类型RMQArray_&lt;T&gt;实现它:

/// Index for RMQArray_<>. It gives us the Index<> interface for all
/// RMQArrayImpl wrapped in RMQArray_<>.
impl<T> std::ops::Index<Idx> for RMQArray_<T>
where
    T: RMQArrayImpl,
{
    type Output = Val;
    fn index(&self, index: Idx) -> &Val {
        self.0.val(index)
    }
}

我还添加了Deref 和DerefMut,这样我就可以在没有索引的情况下访问包装的类型。我只是真的需要它来测试,但现在它无论如何都在这里......

// Deref gives us access to the inner workings of T without
// going through the zero'th index in the wrapper.
impl<T> std::ops::Deref for RMQArray_<T>
where
    T: RMQArrayImpl,
{
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<T> std::ops::DerefMut for RMQArray_<T>
where
    T: RMQArrayImpl,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

从这里开始,它只是为某些类型TImpl 实现RMQArrayImpl,然后将类型包装到type T = RMQArray_&lt;TImpl&gt;:

/// Implements RMQ by running through the [i,j) interval
/// and finding the index with the smallest value.
/// O(1) preprocessing and O(n) access.
pub struct BruteForceRMQImpl {
    values: Vec<u32>,
}

impl RMQArrayImpl for BruteForceRMQImpl {
    fn new(values: Vec<Val>) -> BruteForceRMQImpl { ... }
    fn len(&self) -> Idx                          { ... }
    fn val(&self, index: Idx) -> &Val             { ... }
    fn rmq(&self, i: Idx, j: Idx) -> Idx          { ... }
}

// This is the BruteForceRMQ type that gets the index from the wrapper
// type...
pub type BruteForceRMQ = RMQArray_<BruteForceRMQImpl>;


/// Implements RMQ by table lookup. Has a complete table of all [i,j),
/// so uses O(n²) memory, takes O(n²) time preprocessing, but then
/// does RMQ in O(1).
pub struct FullTabulateRMQImpl {
    values: Vec<u32>,
    rmq: InterTable,
}
pub type FullTabulateRMQ = RMQArray_<FullTabulateRMQImpl>;

impl RMQArrayImpl for FullTabulateRMQImpl {
    fn new(values: Vec<Val>) -> FullTabulateRMQImpl { ... }
    fn len(&self) -> Idx                            { ... }
    fn val(&self, index: Idx) -> &Val               { ... }
    fn rmq(&self, i: Idx, j: Idx) -> Idx            { ... }
}

/// RMQ table that tabulates all [i,i+2^k] ranges (there are O(n log n)),
/// form which we can get the RMQ from the table by splitting [i,j) into
/// two, [i,2^k) and [j-2^k,j) (where k is the largest such k). We can get
/// the RMQ from those two intervals with a table lookup in O(1) and then
/// pick the one of those with the smallest value.
/// The result is O(n log n) preprocessing and O(1) lookup.
pub struct PowerRMQImpl {
    lcp: Vec<Val>,
    tbl: TwoD,
}

impl RMQArrayImpl for PowerRMQImpl {
    fn new(lcp: Vec<u32>) -> PowerRMQImpl { ... }
    fn len(&self) -> Idx                  { ... }
    fn val(&self, index: Idx) -> &Val     { ... }
    fn rmq(&self, i: Idx, j: Idx) -> Idx  { ... }
}

pub type PowerRMQ = RMQArray_<PowerRMQImpl>;

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2013-10-28
    • 2015-08-07
    • 1970-01-01
    • 2021-08-21
    • 2019-08-11
    相关资源
    最近更新 更多