Skip to content

Instantly share code, notes, and snippets.

View aturon's full-sized avatar

Aaron Turon aturon

View GitHub Profile
@aturon
aturon / multi-interop.rs
Created October 13, 2014 17:44
multidispatch woes
/// A trait for types that can be converted from a given error type `E`.
pub trait FromError<E> {
/// Perform the conversion.
fn from_error(err: E) -> Self;
}
// Any type is convertable from itself
impl<E> FromError<E> for E {
fn from_error(err: E) -> E {
err
@aturon
aturon / super-vtable.rs
Created September 22, 2014 19:47
Interaction of `where` clauses, supertraits, and vtables
trait Foo {
fn foo(&self);
}
trait Bar: Foo {}
fn take_bar(b: &Bar) {
b.foo()
}
trait Foo {
fn method(&self) {
println!("in Foo")
}
}
impl<T> Foo for T {}
trait Bar {
fn method(&self) {
trait IntoIterator {
type A;
type I: Iterator<A=A>;
fn into_iter(self) -> I;
}
trait Iterable<'a> {
type A;
type I: Iterator<A=&'a A>;
trait IntoIterator {
type A;
type I: Iterator<A=A>;
fn into_iter(self) -> I;
}
trait IntoDoubleEndedIterator: IntoIterator
where Self::I: DoubleEndedIterator {}
trait Borrowed for Sized? {
type Owned;
fn to_owned(&self) -> Owned;
fn borrow(&Owned) -> &Self;
fn borrow_mut(&mut Owned) -> &mut Self;
}
// This has an implicit Sized bound, so the impls below would
// be allowed with full trait reform
impl<A: Clone> Borrowed for A {
@aturon
aturon / more_equiv.rs
Last active August 29, 2015 14:06
Another take on the equiv problem
// This approach is an alternative to the Equiv trait that
// takes advantage of multidispatch to sidestep coherence problems.
// The basic idea is just to give possibly multiple types that a given
// type can (immutably) "borrow" to -- with an implicit &.
// For most types, A borrows to A. But e.g. String *also* borrows to str.
// We get a nice blanket impl for Borrow, which means that there's
// little risk of forgetting to impl (unlike the ContainerKey approach).
// Also:
@aturon
aturon / any.rs
Last active August 29, 2015 14:05
/// The `Any` trait is implemented by all `'static` types, and can be used for
/// dynamic typing
///
/// Every type with no non-`'static` references implements `Any`, so `Any` can
/// be used as a trait object to emulate the effects dynamic typing.
#[stable]
pub trait Any: AnyPrivate {
/// Returns true if the boxed type is the same as `T`
#[inline]
#[stable]
// Example 1: Overloading for "by need" values: pass in either a value or a thunk to compute it
trait ByNeed<T> {
fn compute(self) -> T;
}
impl<T> ByNeed<T> for T {
fn compute(self) -> T {
self
}
@aturon
aturon / hkt-via-ai-take-2.rs
Last active August 29, 2015 14:05
An updated HKT encoding
trait StarToStar<Input> {
type Output;
}
type Apply<Name, Elt> where Name: StarToStar<Elt> = Name::Output;
struct Vec_;
struct DList_;
impl<T> StarToStar<T> for Vec_ {
type Output = Vec<T>;