3 ms·
I 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
by twic 12y ago
I 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