Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: using traits/typeclasses to implement a generic numeric function

I have a function which works to make a linked list of integers:

enum List<T> { Cons(T, ~List<T>), End }

fn range(start: int, end: int) -> ~List<int> {
    if start >= end { ~End }
    else { ~Cons(start, range(start+1, end)) }
}

However, I want to make a range of any numeric type, including uints, doubles and the like. But this, for example, doesn't work:

fn range<T: ord>(start: T, end: T) -> ~List<T> {
    if start >= end { ~End }
    else { ~Cons(start, range(start+1, end)) }
}

which produces:

> rustc list.rs
list.rs:3:12: 3:15 error: use of undeclared type name `ord`
list.rs:3 fn range<T: ord>(start: T, end: T) -> ~List<T> {
                      ^~~
error: aborting due to previous error

How can I make a generic function in rust which restricts itself to be callable by "numeric" types? Without having to specifically write the interface myself? I had assumed that there were a number of standard-library traits (such as those listed in section 6.2.1.1 of the manual like eq, ord, etc, though now I'm wondering if those are proper "traits" at all) that I could use when declaring generic functions?

like image 621
limp_chimp Avatar asked Jun 10 '13 05:06

limp_chimp


2 Answers

The traits are usually uppercase. In this case it is Ord. See if that helps.

like image 185
MFlamer Avatar answered Nov 02 '22 15:11

MFlamer


In the current master, there is a trait named 'Num' which serves as a general trait for all numeric types. Work has been done recently to unify many of the common math functions to work on this trait rather than u8, f32, etc , specifically.

See https://github.com/mozilla/rust/blob/master/src/libstd/num/num.rs#L26 for the aforementioned Num trait.

Hope this helps!

like image 38
Ron Dahlgren Avatar answered Nov 02 '22 13:11

Ron Dahlgren