Last active
December 20, 2015 16:19
-
-
Save gavinb/6160470 to your computer and use it in GitHub Desktop.
Troubles with types, iterators and collections
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() { | |
// Match parsed group lengths with expected - test data | |
let group_lengths: ~[(&int, &int)] = ~[(&8, &8), (&4, &4), (&4, &4), (&4, &4), (&8, &12)]; | |
// ~~~ | |
// ~~~ Problem 1: all vs take_while and unpacking tuple | |
// ~~~ | |
// This works | |
let glm = group_lengths.iter().all(|&(&a, &b)| a == b); | |
// But this doesn't | |
// let glm = group_lengths.iter().take_while(|&(&a, &b)| a == b); | |
// error: mismatched types: expected `&(&uint,&uint)` but found tuple (types differ) | |
// Had to change to this | |
let glm = group_lengths.iter().take_while(|&v| v.first() != v.second()); | |
// Question: why can Rust unpack the tuple for all() but not take_while() ? | |
// ~~~ | |
// ~~~ Problem 2: collect and types | |
// ~~~ | |
// So we have a valid iterator, we just want to collect into a vector. | |
// The type of the vector is known as it should match group_lengths | |
// since take_while() has to return elements from group_lengths. | |
// Just add collect? No, this fails: | |
let glm = group_lengths.iter().take_while(|&v| v.first() != v.second()).collect(); | |
// error: cannot determine a type for this bounded type parameter: unconstrained type | |
// Ok so we add a type, same as group_lengths | |
let glm: ~[(&int, &int)] = group_lengths.iter().take_while(|&v| v.first() != v.second()).collect(); | |
// error: expected std::iterator::FromIterator<&(&int,&int),std::iterator::TakeWhile<,&(&int,&int),std::vec::VecIterator<,(&int,&int)>>>, | |
// but found std::iterator::FromIterator<(&int,&int),<V2943>> (expected &-ptr but found tuple) | |
// error: cannot determine a type for this bounded type parameter: unconstrained type | |
// Try all sorts of crazy combinations and end up with this still not working... | |
let glm: ~[(&int, &int)] = group_lengths.iter().take_while(|&v| v.first() != v.second()).collect::<~[&(&int, &int)]>(); | |
// error: mismatched types: expected `~[(&int,&int)]` but found `~[&(&int,&int)]` (expected tuple but found &-ptr) | |
// Question: how can we collect the results from an iterator with the type vector of tuples? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment