4 ms·
I don't have NaNs in my list. That's an invariant I would be happy to express in the type system.
by alextgordon 12y ago
I don't have NaNs in my list. That's an invariant I would be happy to express in the type system.
- kaoD 12y agoThen you need another type. A float has NaNs and Rust knows it and prevents you from possibly shooting yourself in the foot.
- steveklabnik 12y agoA 'newtype wrapper' has your back in that situation, which lets you do exactly that.
- sanderjd 12y agoYep, and that type can have a total order and work with the `sort` method with no further ceremony. That actually might be a nice type to have in the standard library. It seems like it would be widely useful, but I'm not sure where it would fit in on cargo.
- twic 12y agoI had a crack at this. This is about the third Rust program i've ever written, so it's probably chock full of noob mistakes: #![feature(std_misc)] mod natural { use std::num::Float; use std::iter::IntoIterator; use std::iter::FromIterator; use std::cmp::Ord; use std::cmp::Ordering; #[derive(PartialEq, PartialOrd, Debug)] pub struct Natural(f64); impl Natural { pub fn new(value: f64) -> Option<Natural> { match value { x if Float::is_nan(x) => None, _ => Some(Natural(value)) } } pub fn new_all<'a, A: IntoIterator<Item=&'a f64>, B: FromIterator<Natural>>(values: A) -> B { let b: B = values.into_iter().map(|f| Natural::new(*f).unwrap()).collect(); b } } impl Eq for Natural { } impl Ord for Natural { fn cmp(&self, other: &Self) -> Ordering { self.partial_cmp(other).unwrap() } } } use natural::Natural; fn main() { let fs = [3.0, 1.0, 1.0]; let mut xs: Vec<Natural> = Natural::new_all(&fs); println!("before = {:?}", xs); xs.sort(); println!("after = {:?}", xs); } In particular, the assignment of the return value of new_all to a local is ugly, but i couldn't figure out how to please the type checker without it.
- sanderjd 12y agoNeat! My version with some mostly superficial changes[0]. Note that we haven't actually removed the panic in the `Ord` implementation! Which is because we've eliminated what we believe is the source of the ordering uncertainty (the NaN), but the type system still doesn't know that.
- sanderjd 12y agoWhoops, didn't post the link: http://goo.gl/7AZxa6 http://goo.gl/7AZxa6