Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/libcore/int-template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ pub pure fn sub(x: T, y: T) -> T { x - y }
pub pure fn mul(x: T, y: T) -> T { x * y }
#[inline(always)]
pub pure fn div(x: T, y: T) -> T { x / y }

/**
* Returns the remainder of y / x.
*
* # Examples
* ~~~
* assert int::rem(5 / 2) == 1;
* ~~~
*
* When faced with negative numbers, the result copies the sign of the
* dividend.
*
* ~~~
* assert int::rem(2 / -3) == 2;
* ~~~
*
* ~~~
* assert int::rem(-2 / 3) == -2;
* ~~~
*
*/
#[inline(always)]
pub pure fn rem(x: T, y: T) -> T { x % y }

Expand All @@ -70,8 +91,24 @@ pub pure fn is_nonpositive(x: T) -> bool { x <= 0 as T }
#[inline(always)]
pub pure fn is_nonnegative(x: T) -> bool { x >= 0 as T }

/**
* Iterate over the range [`lo`..`hi`)
*
* # Arguments
*
* * `lo` - lower bound, inclusive
* * `hi` - higher bound, exclusive
*
* # Examples
* ~~~
* let mut sum = 0;
* for int::range(1, 5) |i| {
* sum += i;
* }
* assert sum == 10;
* ~~~
*/
#[inline(always)]
/// Iterate over the range [`lo`..`hi`)
pub fn range(lo: T, hi: T, it: fn(T) -> bool) {
let mut i = lo;
while i < hi {
Expand Down
38 changes: 36 additions & 2 deletions src/libcore/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,23 @@ pub pure fn connect<T: Copy>(v: &[~[T]], sep: &T) -> ~[T] {
r
}

/// Reduce a vector from left to right
/**
* Reduces a vector from left to right.
*
* # Arguments
* * `z` - initial accumulator value
* * `v` - vector to iterate over
* * `p` - a closure to do operate on vector elements
*
* # Examples
*
* Sum all values in the vector [1, 2, 3]:
*
* ~~~
* vec::foldl(0, [1, 2, 3], |a, b| a + *b);
* ~~~
*
*/
pub pure fn foldl<T, U>(z: T, v: &[U], p: fn(t: T, u: &U) -> T) -> T {
let mut accum = z;
let mut i = 0;
Expand All @@ -936,7 +952,25 @@ pub pure fn foldl<T, U>(z: T, v: &[U], p: fn(t: T, u: &U) -> T) -> T {
return accum;
}

/// Reduce a vector from right to left
/**
* Reduces a vector from right to left. Note that the argument order is
* reversed compared to `foldl` to reflect the order they are provided to
* the closure.
*
* # Arguments
* * `v` - vector to iterate over
* * `z` - initial accumulator value
* * `p` - a closure to do operate on vector elements
*
* # Examples
*
* Sum all values in the vector [1, 2, 3]:
*
* ~~~
* vec::foldr([1, 2, 3], 0, |a, b| a + *b);
* ~~~
*
*/
pub pure fn foldr<T, U: Copy>(v: &[T], z: U, p: fn(t: &T, u: U) -> U) -> U {
let mut accum = z;
for rev_each(v) |elt| {
Expand Down