HKT via trait objects

Is this HKT or is it bogus?

// Type class of all unary type constructors
trait Unary {}

trait Collection<K,T> where K: Unary {
    fn as_any(&mut self) -> &mut dyn std::any::Any;
    fn push(&mut self, x: T);
    fn iterate<'a>(&'a self) -> Box<dyn Iterator<Item=T>+'a>
    where T: Clone;
}

trait CollectionNew {
    fn new<T: 'static>() -> Box<dyn Collection<Self,T>>;
}

fn map_to_string<K,T>(a: &dyn Collection<K,T>)
-> Box<dyn Collection<K,String>>
where K: Unary+CollectionNew, T: ToString+Clone
{
    let mut b = K::new::<String>();
    for x in a.iterate() {
        b.push(x.to_string());
    }
    return b;
}

// Vec without type argument
struct TypeVec;

impl TypeVec {
    fn downcast<T: 'static>(mut a: Box<dyn Collection<Self,T>>)
    -> Vec<T>
    {
        if let Some(v) = a.as_any().downcast_mut::<Vec<T>>() {
            std::mem::replace(v,Vec::new())
        }else{
            unreachable!();
        }
    }
}

impl Unary for TypeVec {}

impl CollectionNew for TypeVec {
    fn new<T: 'static>() -> Box<dyn Collection<Self,T>> {
        Box::new(Vec::new())
    }
}

impl<T: 'static> Collection<TypeVec,T> for Vec<T> {
    fn as_any(&mut self) -> &mut dyn std::any::Any {self}
    fn push(&mut self, x: T) {self.push(x);}
    fn iterate<'a>(&'a self) -> Box<dyn Iterator<Item=T>+'a>
    where T: Clone
    {
        Box::new(self.iter().cloned())
    }
}

fn main() {
    let a: Vec<i32> = vec![1,2,3,4];
    let b: Vec<String> = TypeVec::downcast(map_to_string(&a));
    println!("{:?}",b);
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.