Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A 'newtype wrapper' has your back in that situation, which lets you do exactly that.


Yep, 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.


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.


Neat! 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.


Whoops, didn't post the link: http://goo.gl/7AZxa6




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: