Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active January 12, 2023 22:23
Show Gist options
  • Save fvilante/4b4f770e8238e9a1618c9f54b20ac659 to your computer and use it in GitHub Desktop.
Save fvilante/4b4f770e8238e9a1618c9f54b20ac659 to your computer and use it in GitHub Desktop.
Sketch of a Closure-like mecanism in no_std rust
// -----
struct Wrapper<A: Copy> {
value: A
}
impl<A: Copy> Wrapper<A> {
fn new(value: A) -> Self {
Self {
value,
}
}
fn map<E, B, F: Closure<E,A,B>>(&self, f: F) -> B {
f.run(self.value)
}
}
// -----
trait Closure<E,A,B> {
fn new(env: E, f: fn(E,A) -> B) -> Self;
fn run(&self, value: A) -> B;
}
struct MyClosure<E,A,B> {
env: E,
f: fn(E,A) -> B,
}
impl<E: Copy,A: Copy,B> Closure<E,A,B> for MyClosure<E,A,B> {
fn new(env: E, f: fn(E,A) -> B) -> Self {
Self {
env,
f,
}
}
fn run(&self, value: A) -> B {
(self.f)(self.env, value)
}
}
fn main() -> () {
let one = 77;
let another = 23;
let value: u8 = 10;
let a: Wrapper<u8> = Wrapper::new(value);
let b = a.map( MyClosure::new((one, another), |env, a| {env.0+env.1+a}));
println!("value is {b} which is {one} plus {another} plus {value}.")
// output:
// value is 110 which is 77 plus 23 plus 10.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment