Created
August 4, 2016 06:47
-
-
Save Svetixbot/e4d3a13087850676e5844bb817567329 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 1. this: | |
| if a.is_none() || c == std::u64::MAX { | |
| None | |
| } else { | |
| a.unwrap().checked_add(c) | |
| } | |
| can be replaces with (not sure if it compiles though...): | |
| a.and_then(|value| value.checked_add(c)) | |
| 2. Once you start using Option for something in your code, you have to use Option everywhere, otherwise composition looks horrible. | |
| But I don't really get iterators. I think you can do this(this definetly won't compile): | |
| impl Iterator for PeasantTables { | |
| type Item = Entry; | |
| fn next(&mut self) -> Option<Entry> { | |
| // Can we make an assumption that self.next will give you an Option<Entry> ? | |
| // is it possible? | |
| let current: Option<Entry> = Entry { ..self.next }; | |
| // the composition would look like this. As you can see, it is hard to read: | |
| let result = current.and_then(|entry| entry.first.checked_mul(2). | |
| and_then(|first| entry.second.checked_div(2)). | |
| map(|second| Entry {first: first, second: second})) | |
| // if only RUST had list comprehansions the above code would look like this: | |
| let result = for { | |
| entry <- current | |
| first <- entry.first.checked_mul(2) | |
| second <- entry.second.checked_div(2) | |
| } yield Entry {first: first, second: second} | |
| // but even though you can make it readable with pattern matching which should work in Rust: | |
| let result = current.and_then{|entry| | |
| match (entry.first.checked_mul(2), entry.second.checked_div(2)) { | |
| (Some(first), Some(second)) => Entry {first: first, second: second} | |
| _ => None | |
| } | |
| } | |
| self.next = result | |
| result | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nono @sragu, you shouldn't have Option of i64, that would be wrong for the reasons you just said: entry with either invalid first/second is invalid state. What I mean is that once you decide to use Option, it has to be an Option for self.next as well.