Last active
December 23, 2015 12:37
-
-
Save zummenix/c3d9e062ee1a5d25eee0 to your computer and use it in GitHub Desktop.
Lenses in rust (example prototype)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let person1 = Person::new("Ted".to_owned(), 14); | |
let name_lens = Person::name_lens(); | |
let person2 = (name_lens.set)(&person1, "Doe".to_owned()); | |
let person3 = (name_lens.set)(&person2, (name_lens.get)(&person1)); | |
let person3 = (Person::age_lens().set)(&person3, 22); | |
println!("person1 {:?}", person1); | |
println!("person2 {:?}", person2); | |
println!("person3 {:?}", person3); | |
} | |
#[derive(Debug)] | |
pub struct Person { | |
name: String, | |
age: u32, | |
} | |
impl Person { | |
pub fn new(name: String, age: u32) -> Self { | |
Person { name: name, age: age } | |
} | |
pub fn name_lens() -> Lens<Person, String> { | |
Lens { | |
get: Box::new(|p: &Person| p.name.clone()), | |
set: Box::new(|p, name| Person::new(name, p.age)), | |
} | |
} | |
pub fn age_lens() -> Lens<Person, u32> { | |
Lens { | |
get: Box::new(|p: &Person| p.age), | |
set: Box::new(|p, age| Person::new(p.name.clone(), age)), | |
} | |
} | |
} | |
pub struct Lens<A, B> { | |
pub get: Box<Fn(&A) -> B>, | |
pub set: Box<Fn(&A, B) -> A>, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment