Skip to content

Instantly share code, notes, and snippets.

@msullivan
Created July 2, 2012 20:27
Show Gist options
  • Save msullivan/3035496 to your computer and use it in GitHub Desktop.
Save msullivan/3035496 to your computer and use it in GitHub Desktop.
frumious hack for static typeclass methods
iface builder<A> {
// These "static" methods ignore their self parameter
fn __new_container() -> self;
fn __push(&_v: self, +_x: A);
}
impl extensions<A: copy> of builder<A> for ~[A] {
fn __new_container() -> ~[A] { ~[] }
fn __push(&v: ~[A], +x: A) { vec::push(v, x); }
}
unsafe fn make_bs_builder<A,IA:builder<A>>() -> IA {
unsafe::reinterpret_cast(ptr::null::<u8>())
}
// Pretend that these are static typeclass methods
fn new_container<A,IA:builder<A>>() -> IA {
unsafe { make_bs_builder::<A,IA>().__new_container() }
}
fn push<A,IA:builder<A>>(&v: IA, +x: A) {
unsafe { make_bs_builder::<A,IA>().__push(v, x) }
}
fn build_from_vec<A:copy,IA:builder<A>>(v: &[A]) -> IA {
let mut new_v = new_container();
for v.each() |x| {
push(new_v, x);
}
ret new_v;
}
fn main() {
let x: ~[int] = build_from_vec([1,2,3]/_);
log(error, x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment