Skip to content

Instantly share code, notes, and snippets.

@ferranpujolcamins
Created November 23, 2021 12:07
Show Gist options
  • Save ferranpujolcamins/b088f88df33fa76eb757c1561897e492 to your computer and use it in GitHub Desktop.
Save ferranpujolcamins/b088f88df33fa76eb757c1561897e492 to your computer and use it in GitHub Desktop.
A Rust implementation of data Ext b = forall a. Ext a (a -> b)
struct ExistsPrivate<A, F, B>
where F: Fn(&A) -> B {
a: A,
f: F
}
trait AnyExistsPrivate<B> {
fn extract(&self) -> B;
}
impl<A, F, B> AnyExistsPrivate<B> for ExistsPrivate<A, F, B>
where F: Fn(&A) -> B {
fn extract(&self) -> B {
(self.f)(&self.a)
}
}
struct Exists<'a, B>(Box<dyn AnyExistsPrivate<B> + 'a>);
impl<'a, B: 'a> Exists<'a, B> {
fn new<A: 'a, F: 'a>(a: A, f: F) -> Exists<'a, B>
where F: Fn(&A) -> B {
Exists(Box::new(ExistsPrivate {
a: a,
f: f
}))
}
fn extract(&self) -> B {
self.0.extract()
}
}
fn main() {
let e = Exists::new(0, |i: &i32| i+1);
println!("{}", e.extract());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment