Created
September 27, 2017 11:22
-
-
Save anonymous/d04d30ba8e405dd3ad280a249a7a96eb to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
#![feature(conservative_impl_trait)] | |
use std::iter::{self}; | |
fn main() { | |
println!("{:?}", difference([0, 1, 2].iter(), [2, 3, 4].iter()).collect::<Vec<_>>()); | |
println!("{:?}", union([0, 1, 2].iter(), [2, 3, 4].iter()).collect::<Vec<_>>()); | |
println!("{:?}", intersection([0, 1, 2].iter(), [2, 3, 4].iter()).collect::<Vec<_>>()); | |
} | |
fn difference<A, B, I>(a: A, b: B) -> impl Clone + Iterator<Item=I> where A: Clone + Iterator<Item=I>, B: Clone + Iterator<Item=I>, I: Clone + Eq { | |
fn filter<A, I>(v: (I, A)) -> Option<I> where A: Clone + Iterator<Item=I>, I: Clone + Eq { | |
fn eq<I>(i: (I, &I)) -> bool where I: Eq { | |
i.0 == *i.1 | |
} | |
if !v.1.zip(iter::repeat(&v.0)).any(eq) { | |
Some(v.0) | |
} else { | |
None | |
} | |
} | |
a.zip(iter::repeat(b)).filter_map(filter) | |
} | |
fn union<A, B, I>(a: A, b: B) -> impl Clone + Iterator<Item=I> where A: Clone + Iterator<Item=I>, B: Clone + Iterator<Item=I>, I: Clone + Eq { | |
a.clone().chain(difference(b, a)) | |
} | |
fn intersection<A, B, I>(a: A, b: B) -> impl Clone + Iterator<Item=I> where A: Clone + Iterator<Item=I>, B: Clone + Iterator<Item=I>, I: Clone + Eq { | |
fn filter<A, I>(v: (I, A)) -> Option<I> where A: Clone + Iterator<Item=I>, I: Clone + Eq { | |
fn eq<I>(i: (I, &I)) -> bool where I: Eq { | |
i.0 == *i.1 | |
} | |
if v.1.zip(iter::repeat(&v.0)).any(eq) { | |
Some(v.0) | |
} else { | |
None | |
} | |
} | |
a.zip(iter::repeat(b)).filter_map(filter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment